| <<< C++ struct destructor | Index | The need for a copy constructor >>> |
Unfortunately, there is a huge problem in our solution: the way it's written, the same memory may be deleted twice:
int main()
{
Rectangle rect( "first", 333, 222 );
Rectangle rect2 = rect; // this makes a "shallow" copy
// this deletes memory imporperly "owned" by both objects
rect2.set_name( "second" );
//...
return 0;
// When destructor of rect is invoked, the memory that it
// thinks it is managing is already deallocated!
// depending on your circumstances, you may or not crash
// here..
}
In a larger program that has a potential of using hundreds or even thousands of Rectangle struct instances in memory, the code will corrupt memory and mess up the C++ free store manager that allocates and deallocates our dynamic memory.
| <<< C++ struct destructor | Index | The need for a copy constructor >>> |