Stack objects are processed automatically by the compiler.
When a scope is left, it is deleted.
{ obj a; }
When you do the same with the βnewβ object, you get a memory leak:
{ obj* b = new obj; }
b is not destroyed, so we have lost the ability to recover memory b. And maybe worse, the object cannot clean itself.
The following is common in C:
{ FILE* pF = fopen( ... ); // ... do sth with pF fclose( pF ); }
In C ++ we write the following:
{ std::fstream f( ... );
When we forget to call fclose in Example C, the file is not closed and cannot be used by other programs. (for example, it cannot be deleted).
Another example demonstrating a line of an object that can be built, assigned, and which is destroyed when leaving the area.
{ string v( "bob" ); string k; v = k
source share