Search code examples
c++visual-studio-expressvisual-studio-2010

how to make smart pointer go out of scope at exit()


I've spent a bit of time writing an application for practice and i've taken a liking to using smart pointers throughout so as to avoid memory leaks in case i forgot to delete something. At the same time, i've also taken a liking to using exceptions to report failure in a constructor and attempt to handle it. When it cannot however, i would like for it to exit the program at that spot either through a call to assert() or exit(). However, using the crtdbg library in msvc, it reports a memory leak from the smart pointers that have anything dynamically allocated to them. This means one of two things to me. 1) the smart pointers never went out of scope of where they were allocated, and never deallocate, causing some memory leaks, or 2) crtdbg is not catching the deallocation because it doesn't exit at main. From this page though, using _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); at the begginning of the program will catch the leaks from any exit point, and I still get the memory leak errors using that.

So my question to you guys, will the memory actually be deallocated at exit or assert, and if not, might i be able to derive from std::shared_ptr and implement my own solution to cataloging dynamically allocated objects to be deallocated just before the call to exit or assert, or is that too much work for a more simple solution?


Solution

  • When the program exits, the memory is reclaimed by the OS anyway, so if leaking is worrying you, it shouldn't.

    If, however, you have logic in your destructors, and the objects must be destroyed - calling exit explicitly bypasses all deallocation. A workaround for this is to throw an exception where you would call exit, catch it in main and return.

    #include "stdlib.h"
    
    void foo()
    {
       //exit(0);
       throw killException();
    }
    
    int main
    {
       try
       {
          foo();
       }
       catch (killException& ex)
       {
          //exit program calling destructors
          return EXIT_FAILURE;
       }
    }