Memory Management


I have a general question about memory management. I know that one can create custom constructors and destructors for one's custom classes. I also know that one can use the custom destructor to free all of the memory that a given object instance of a class uses thereby freeing memory upon deletion. However, I read somewhere that this is not the best practice for memory management. What is a good approach to memory management as it relates to object creation and deletion in c++?

Thank you
you only need to manage memory if you use the 'new' keyword, even then you can use std::unique_ptr<classname> new Object or std::shared_ptr<classname> new Object, and then you don't have to worry about deleting what you 'newed'
The idiom you are talking about is called RAII*. What did that source recommended instead of using RAII? In what context did it recommended something else?

Last edited on
Unfortunately I cannot find the resource again and therefore I cannot tell you what else it recommended. If you recommend a different technique, such as the two mentioned above, I'd love to hear more about them.

re: Zephilinox's reply, I have not used those constructors before, what exactly is it that they do?
unique_ptr and shared_ptr hold a ptr to an object of the type that you specified in its template argument '<classname>' so that you don't have to manually delete it yourself, it will automatically be deleted when it goes out of scope (RAII).

So far I've only used the unique_ptr, which ensures there is only 1 ptr pointing to that object, but I believe shared_ptr allows duplicates to be made.

it's basically a really minor form of manual garbage collecting, the overhead is so minimal, there are plenty of articles talking about these, and they were often implemented as user-defined classes called auto_ptr, but now C++11 supports them as part of the language.
unique_ptr and shared_ptr are so called smart pointers.

Zephilinox wrote:
they were often implemented as user-defined classes called auto_ptr

std::auto_ptr is a template class in the C++ standard library. It was deprecated in C++11.
Last edited on
I know I've seen libraries implement their own version of a 'smart pointer', I thought they called it auto_ptr, I could easily be wrong, maybe they did simply call it smart_ptr, either way it isn't that important and someone could have called it banana_cakes for all we know.
So am I to understand that once I delete this pointer the object which the pointer pointed to is automatically freed in memory?
Topic archived. No new replies allowed.