C++ new and delete statements

Associate
Joined
22 Jul 2004
Posts
230
Location
Nottingham, UK
Look at the code below.

Code:
string A, B;

CT2CA* aTemp = new CT2CA( frmAdd->A );
A = string( *aTemp );

aTemp = new CT2CA( frmAdd->B );
A = string( *aTemp );

delete aTemp;

My question is; when i call the 2nd new statement does the previous class get deleted, or do i have todo that manually?
 
You have to delete it yourself, replacing the pointer means you have no way to delete it later, but it's still allocated - a memory leak. If you want some kind of automatic memory managment, look-up reference couting via wrapper classes - "smart" pointers; std::auto_ptr is one such implementation.
 
Last edited:
matja said:
...replacing the pointer means you have no way to delete it later...

...from within the same executable.
the memory will be released back to the system when the executable terminates.

in some circumstances, this might be acceptable behaviour, but in the general case you really should be releasing your allocated resources once you have finished with them.
 
matja said:
You have to delete it yourself, replacing the pointer means you have no way to delete it later, but it's still allocated - a memory leak. If you want some kind of automatic memory managment, look-up reference couting via wrapper classes - "smart" pointers; std::auto_ptr is one such implementation.

There are very few situations where auto_ptr is a recommended solution - its not really a 'smart pointer' in the sense that ist not reference counted.

One should really look to Boost's shared pointer for this, as it fully implements the RAII idiom.
 
Back
Top Bottom