I’m a c++ newbie, my code currently new’s up on the heap in several places without calling delete. I know I need to do something about this.
My typical usage is where I new up a class instance in another classes member method then the method returns the pointer to the object.
If i change the return types from MyType* to std::tr1::shared_ptr will this fix my code to not leak memory?
Thanks a lot.
Edit:
Also likewise, I currently store new’ed up objects as MyType* as a value in a std:map. This map is a private member to a class instance. If I simply change this to std::tr1::shared_ptr will this clear up these when it’s owner (class) falls out of scope?
Thanks again
It’s a reasonable band-aid, sure.
A shared pointer is a reference-counted pointer. So as long as one or more
shared_ptrs exist pointing to an object, that object will be kept alive. The problem occurs if you have circular references. Then the reference count will never reach 0, and the object(s) will never be deleted.So
shared_ptr* still* require you to understand what you’re doing and think about object ownership, as you always have to do in C++. But it simplifies some otherwise complex scenarios, where determining ownership is hard.But the real fix to your problem is to:
new. Can the object instead be stored on the stack? Can the object be rewritten as a RAII class, so that a small wrapper object is allocated on the stack (or elsewhere with automatic storage duration), and which, through its constructors and destructors, manages a heap-allocated memory resource? Then, as long as that object exists, its allocated memory will be preserved, and once it is destroyed, it will delete its allocated memory.new, put them in one of the smart pointer classes.shared_ptris popular because it is the one that comes closest to looking like a garbage collector, but it isn’t, and if you treat it as one and use it as an excuse to not think about memory management, then it won’t work. Understand all the smart pointer classes (scoped_ptr and auto_ptr in C++03, or unique_ptr replacing both in C++11, shared_ptr and weak_ptr), and use the one that best fits your scenario.deleteyour memory when its destructor is called.There’s no quick and easy fix. The way to handle memory management in C++ is to avoid memory management. Delegate it out to your objects. If you’re calling
deletein your own code, you’re doing it wrong. Often, you don’t even neednew, but if you do, assign ownership to a smart pointer immediately, and let that calldeletefor you.As a rule of thumb, unless you’re a library writer, you shouldn’t write either
newordelete. You should virtually never use raw pointers, and only when it is absolutely necessary, use smart pointers. Let your classes do the heavy lifting. Don’t be afraid to put them on the stack, pass them by value, and let them handle their resources internally.