Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak despite destructor call using static unique_ptr

I use unique_ptr as a static data member to hold a pointer.

struct Test
{
    int i;
    ~Test()
    {
        cout << "destructed" << endl;
    }
};

struct S
{
    static unique_ptr<Test> te;
};
unique_ptr<Test> S::te = unique_ptr<Test>(new Test());

At program termination S::te is destructed which calls the Test-destructor.

But _CrtDumpMemoryLeaks shows me a memory leak on the memory position of S::te.get() which is the pointer to the (destructed) Test-object.

I don't understand this behaviour.

Can't I use a static unique_ptr? Why is there a leak although the destructor is called by the unique_ptr implementation?

like image 866
Qwabbelbelly Avatar asked Mar 22 '23 13:03

Qwabbelbelly


1 Answers

This happens if you attempt to check for leaks before static destruction has occurred.

To fix this, you can call _CrtSetDbgFlag with _CRTDBG_LEAK_CHECK_DF at the beginning of your application; it will automatically invoke _CrtDumpMemoryLeaks at exit, after static destruction.

like image 177
Collin Dauphinee Avatar answered Apr 06 '23 22:04

Collin Dauphinee