Do pointers automatically destroy themselves

Sorry that the topic was very vague, I'll explain better now.
Lets say there's a class, and declared inside the class is a pointer.
When I create an instance of the class in main, and then destroy it, will the pointer in the class be destroyed as well?
Or will it just be left there taking up memory?

Thanks
closed account (S6k9GNh0)
The pointer itself is deallocated. However, any memory that the pointer points to must be taken care of otherwise.
If the pointer in the class points to something that's dynamically allocated, then no. That bit of memory that the class's pointer points to is NOT freed.

This is what the destructor is for!

-Albatross

EDIT: Ninja'd.
Last edited on
Yes, I should have mentioned my memory is dynamically allocated.
So in the destructor I just manually deallocate all my memory?
Yes...
Whatever you do allocate dynamically, have to be deallocated manually.
closed account (S6k9GNh0)
Obligatory mention that that's not neccessarily true. However, in the sense that "every call to new must be met with an explicit delete", that's correct.
Alternatively you could(should?) use unique_ptr<>. It will take care of the destruction of the allocated object pointed to by it(assuming C++11).

See:
http://en.cppreference.com/w/cpp/memory/unique_ptr
+1 Caligulaminus

If you are manually cleaning up, you're probably doing it wrong.

You should always use some kind of container to manage memory (ie: prefer unique_ptr over using a raw pointer for dynamic memory). Or at least... you should do so whenever practical -- which is most of the time.
Topic archived. No new replies allowed.