简体   繁体   English

C++ 释放静态变量

[英]C++ freeing static variables

I would like my class to have a static pointer to a dynamically allocated region of memory.我希望我的班级有一个指向动态分配的内存区域的静态指针。 I understand how to initialize it - in my case I will initialize it when the first object needs it.我了解如何初始化它 - 就我而言,我将在第一个对象需要它时对其进行初始化。 However, I don't know when/where in the code to free it.但是,我不知道在代码中何时/何地释放它。 I'd like to free it when the program terminates.我想在程序终止时释放它。

I might be able to free the pointer in my objects' destructor, but then I'd have to maintain an object count to see if it's safe to free when the object is the last object in use.我可能能够在对象的析构函数中释放指针,但随后我必须维护一个对象计数,以查看当对象是最后一个正在使用的对象时释放是否安全。

Is there a more elegant way to do this?有没有更优雅的方法来做到这一点?

Please let me know.请告诉我。

Thanks, jbu谢谢,jbu

You have two solutions here:您在这里有两种解决方案:

  1. Don't delete delete it (you're in C++, you use new and delete, right? ;) ).不要删除删除它(你在 C++ 中,你使用 new 和 delete,对吧?;))。 Almost all OSes today will "free" the memory allocated by the application anyway once it's finished.今天几乎所有的操作系​​统都会在应用程序完成后“释放”应用程序分配的内存。 But that's not a good solution, that make memory leaks hard to detect for example.但这不是一个好的解决方案,例如,这使得内存泄漏难以检测。
  2. Encapsulate your pointer into a class (as member) , then use this class as the type of your static.将您的指针封装到一个类中(作为成员) ,然后使用这个类作为您的静态类型。 That way, you know the class destructor will be called at the end of the application.这样,您就知道将在应用程序结束时调用类析构函数。 You then just delete your data in the destructor and the work is done and clean.然后,您只需删除析构函数中的数据,工作就完成并清理了。 That's the power of RAII.这就是 RAII 的力量。

I suggest you do 2, that's a really clean way to do it.我建议你做 2,这是一个非常干净的方式来做到这一点。


Here is a simple example.这是一个简单的例子。 Instead of doing this而不是这样做

static Thing* things = new Thing(); // or whatever way to initialize, here or in a specific function

You will do that :你会这样做:

class ThingManager // or whatever name you like
{
public:
   ThingManager( Thing* thing ) : m_thing( thing ) { }//or create it here? whatever solution suits your way of creating the data

   ~ThingManager() { delete m_thing; } // THAT's the important part!

    Thing* instance() const { return m_thing; } // or whatever accessor you need, if you need one

private:
    Thing* m_thing;
};

and then进而

static ManagedThing thing; // now i can access it via thing.instance() 

When the program ends, the static variable (that is not pointer anymore) will be destroyed and it's destructor will be called to do that.当程序结束时,静态变量(不再是指针)将被销毁,并且将调用它的析构函数来执行此操作。

It's written just to give you an idea of how you can do that.它的编写只是为了让您了解如何做到这一点。

Throw it in a smart pointer.将其放入智能指针中。 It will have static lifetime and be destroyed after main returns:它将具有静态生命周期并在main返回后被销毁:

static std::auto_ptr<T> thePointer;

Another option is to register your own atexit function:另一种选择是注册您自己的atexit函数:

// static
void YourClass::freePointer(void)
{
    delete getPointer();
}

// static
T* YourClass::getPointer(void)
{
    if (!thePointer)
    {
        thePointer = new T;
        atexit(freePointer);
    }

    return thePointer;
}

Which will have the same effect.这将具有相同的效果。 Another option you already mention is to keep a static counter.您已经提到的另一个选项是保留一个静态计数器。 Note you can actually wrap that up pretty effectively.请注意,您实际上可以非常有效地将其包装起来。

From the OS perspective, there's no real point in freeing memory as your program terminates, all that does is slow termination down.从操作系统的角度来看,在程序终止时释放内存没有任何意义,所做的只是缓慢终止。 Termination of your application tears down your entire address space, it will free everything you allocate on the heap all at once.您的应用程序眼泪就下来了你的整个地址空间终止,这将释放你在堆上分配一下子一切 explicitly calling free on app shutdown is just shuffling pointers in the heap that will get thrown away anyway.在应用程序关闭时显式调用free只是在堆中混洗指针,无论如何都会被丢弃。

The main reason why we try so hard to free everything explicitly is to be sure that we aren't leaking memory and our memory footprint doesn't grow forever.我们如此努力地明确释放所有内容的主要原因是确保我们不会泄漏内存并且我们的内存占用不会永远增长。

But if you can be certain that this is static, that there will be only one, and that you can't safely free it until all of your other objects have been freed, this is a case where it might be better just to let application termination take care of it for you.但是,如果您可以确定这是静态的,并且只有一个,并且在释放所有其他对象之前无法安全地释放它,那么在这种情况下,最好让 application终止为你照顾它。

您可以将静态变量声明为智能指针,然后在程序完成时分配的指针将被释放。

我会在类中定义一个静态计数器来跟踪对象实例计数,因为析构函数执行它会减少计数器,如果 counter== 0 也释放内存..就像你一样

I just came upon this old post when trying to get my own static pointer to get freed up at exit.当我试图让我自己的静态指针在退出时被释放时,我刚刚看到了这篇旧帖子。

The proper C++ (C++11) solution is to use a smart pointer, either std::unique_ptr<T> or std::shared_ptr<T> where T is the type of the object you're initializing.正确的 C++ (C++11) 解决方案是使用智能指针,即std::unique_ptr<T>std::shared_ptr<T> ,其中 T 是您正在初始化的对象的类型。 These templates manage the lifetime of the objects and will delete the objects when they go out of scope or become the last reference in memory, respectively.这些模板管理对象的生命周期,并分别在对象超出范围或成为内存中的最后一个引用时删除对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM