I have been stumbling over this problem for a while now. I am trying to return a pointer to an object to I can say
MyObject* obj = Manager::Create(int i, int j);
How do I correctly allocate memory so there are no leaks? I thought I was supposed to call new to make the memory on the heap but I have recently been told otherwise.
Well… I think you’re a bit confused. Yes, you do call
newto dynamically allocate memory. However, there are common patterns (see; RAII) that are used to avoid it at all costs as it is an easy way to shoot yourself in the foot (read; write bugs).At some point, somethign has to call
newin order to dynamically allocate memory. first though you need to ask yourself; does this need to be dynamically allocated? If the answer is no, then declare it like so and move on.Next, why not store the pointer in a
std::unique_ptror something equivalent? That will take care of management for you, again, you don’t manage the memory;The BOOST library has an equivalent class (
unique_ptris C++11).The point is that memory is being managed by the class via its constructor and destructor. You allocate memory dynamically when you create the object and you deallocate it (i.e., call
delete) in its destructor. You simply stack allocate these in as tight a scope as possible and you don’t have to worry about memory leaks.I write C++ at work every day and I almost never call
newordelete. As a small example, let’s examine this class, which is a trivial implementation of a scoped pointer (note; this is not a “correct” implementation and is overly trivial! This problem is harder to solve than this, but I am using it solely as an example of managing the lifetime of a dynamically allocated object).You may use this class as a wrapper around a pointer to dynamically allocated memory. When it leaves its scope its destructor will be called and the memory will be cleaned up. Again, this is not production quality code! It is not correct in that it lacks several mechanisms that a real world class would need (copy/ownership semantics, a more advanced deallocater, etc.)