简体   繁体   中英

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

You have two solutions here:

  1. 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.
  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.

I suggest you do 2, that's a really clean way to do it.


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:

static std::auto_ptr<T> thePointer;

Another option is to register your own atexit function:

// 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.

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.

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

我会在类中定义一个静态计数器来跟踪对象实例计数,因为析构函数执行它会减少计数器,如果 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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