Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - What does "Stack automatic" mean?

Tags:

c++

oop

In my browsings amongst the Internet, I came across this post, which includes this

"(Well written) C++ goes to great lengths to make stack automatic objects work "just like" primitives, as reflected in Stroustrup's advice to "do as the ints do". This requires a much greater adherence to the principles of Object Oriented development: your class isn't right until it "works like" an int, following the "Rule of Three" that guarantees it can (just like an int) be created, copied, and correctly destroyed as a stack automatic."

I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly?

Can someone give an example?

like image 727
Mike Avatar asked Dec 04 '22 16:12

Mike


1 Answers

Stack objects are handled automatically by the compiler.

When the scope is left, it is deleted.

{
   obj a;
} // a is destroyed here

When you do the same with a 'newed' object you get a memory leak :

{
    obj* b = new obj;
}

b is not destroyed, so we lost the ability to reclaim the memory b owns. And maybe worse, the object cannot clean itself up.

In C the following is common :

{
   FILE* pF = fopen( ... );
   // ... do sth with pF
   fclose( pF );
}

In C++ we write this :

{
   std::fstream f( ... );
   // do sth with f
} // here f gets auto magically destroyed and the destructor frees the file

When we forget to call fclose in the C sample the file is not closed and may not be used by other programs. (e.g. it cannot be deleted).

Another example, demonstrating the object string, which can be constructed, assigned to and which is destroyed on exiting the scope.

{
   string v( "bob" );
   string k;

   v = k
   // v now contains "bob"
} // v + k are destroyed here, and any memory used by v + k is freed
like image 100
Christopher Avatar answered Dec 20 '22 22:12

Christopher