Thread: Memory leaks, and hung up API stuff when using new keyword to make a class

  1. #1
    Registered User
    Join Date
    Jan 2010
    Posts
    206

    Question Memory leaks, and hung up API stuff when using new keyword to make a class

    Hi there,

    Having just recently fixed an issue with memory leaks and DirectX objects still being live after shutdown I was wondering if it's a bad idea to create a class using the 'new' keyword if it contains smart pointers?

    I was using 'new' to make a class that does some basic rendering stuff that worked quite nicely until it came time to close the window and thus the program. The debugger was showing all kinds of issues as mentioned above. I made sure I had a 'delete this' line in the class destructor too.

    Some of the problems experienced were multiple class destructor calls, seemingly infinite amounts of them. I should note that the class gets created inside a DLL file and then a pointer to it is returned to the program that creates the DLL. If that makes any difference.

    However when I just made a global variable of the class type (something I was trying to avoid) there were no problems at all. The only issues I seemed to have was calling the Release methods on the COMPtrs in the destructor showed a memory access issue. Most likely because these smart pointers had already called their release methods when they went out of scope.

    So I'm thinking is this a possibility? Maybe not a good idea to use the rather old keyword 'new' in combination with smart pointers?

    Thanks

  2. #2
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    I'm pretty sure delete this in a class's destructor will cause problems. What happens if an instance of the class was statically or automatically allocated? You can't delete it. And if it's dynamically allocated with new, the destructor will be called when delete is called on the instance.

    So that line will end up trying to delete the same object infinitely, since delete this will invoke the destructor again, which invokes delete this, which invokes the destructor again, ad infinitum, even for objects that shouldn't be deleted in the first place.

  3. #3
    Registered User
    Join Date
    Jan 2010
    Posts
    206
    Great advice thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 10-15-2012, 05:16 PM
  2. Memory usage and memory leaks
    By vsanandan in forum C Programming
    Replies: 1
    Last Post: 05-03-2008, 05:45 AM
  3. Are there any memory leaks here??
    By cmasri in forum C++ Programming
    Replies: 9
    Last Post: 01-18-2007, 01:14 AM
  4. Odd memory leaks
    By VirtualAce in forum C++ Programming
    Replies: 11
    Last Post: 05-25-2006, 12:56 AM
  5. Memory leaks...
    By TonyP in forum C++ Programming
    Replies: 1
    Last Post: 12-22-2002, 02:23 PM

Tags for this Thread