C++ 释放静态变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2429408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ freeing static variables
提问by jbu
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
回答by Klaim
You have two solutions here:
您在这里有两种解决方案:
- Don't delete delete it(you're in C++, you use new and delete, right? ;) ). 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.
- 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.
- 不要删除删除它(你在 C++ 中,你使用 new 和 delete,对吧?;))。今天几乎所有的操作系统都会在应用程序完成后“释放”应用程序分配的内存。但这不是一个好的解决方案,例如,这使得内存泄漏难以检测。
- 将您的指针封装到一个类中(作为成员),然后使用这个类作为您的静态类型。这样,您就知道将在应用程序结束时调用类析构函数。然后,您只需删除析构函数中的数据,工作就完成并清理了。这就是 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.
它的编写只是为了让您了解如何做到这一点。
回答by GManNickG
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.
这将具有相同的效果。您已经提到的另一个选项是保留一个静态计数器。请注意,您实际上可以非常有效地将其包装起来。
回答by John Knoeller
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 everythingyou 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终止为你照顾它。
回答by coelhudo
You can declare you static variable as a smart pointer, then when the program finish the pointer allocated will be freed.
您可以将静态变量声明为智能指针,然后在程序完成时分配的指针将被释放。
回答by Luca Rocchi
i would define a static counter in the class to track object instances count as the destructor get execute it decrement the counter and if counter== 0 free the memory too .. just as you
我会在类中定义一个静态计数器来跟踪对象实例计数,因为析构函数执行它会减少计数器,如果 counter== 0 也释放内存..就像你一样