views:

77

answers:

4

one of the cpp files has a structure pointer created with "new" operator. Should that pointer be explicitly deleted? Or is the pointer automatically deleted?

+6  A: 

C++ does not (normally) have automatic memory management. To free up the memory of that object you would use delete. When to use it is a different question.

EDIT: Also, the pointer will be deleted (or will be overwritten on the stack) when the function returns, but the object pointed at will stay in the heap until you delete it.

Jared Updike
+1 for "*When* to use it is a different question."
André Caron
+1  A: 

The use of the 'new' keyword will allocate memory on the heap, the same way 'malloc' does in C. To get that memory back when you're done using it, you have to do a 'delete' on the pointer returned from the 'new'.

This is easy when the life of some object does not extend outside the function where it was instantiated, but becomes more complicated when these objects are returned or added to collections...

MStodd
+1  A: 

As @Jared Updike notes, you have to do this by yourself. That's one reason why smart pointers such as those in Boost and C++0x are so widely used - they are lightweight classes that manage an underlying raw memory pointer, to avoid memory leaks when (not if) you forget to delete or delete[] raw pointers.

If you are new to C++ do yourself a favour and take a look at those (scoped_ptr, shared_ptr etc).

Steve Townsend
+1  A: 

If you are looking for easier memory management, you may want to look at Shared Pointers . They are a convenient way to assure you that the memory will be freed if correclty used.

Matthieu