Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is object created without new operator deleted in a specific case in C++

If we have the following code snippet:

MyObject my_object = MyObject(0);
my_object = MyObject(1);

What happens to MyObject(0)? Is it deleted? Looking at what I have read about it it should only be deleted when we leave the scope of creation, so the anwser is probably no. If this is the case is there any way to explicitly delete it other than using pointers?

like image 758
siemanko Avatar asked Sep 02 '11 05:09

siemanko


2 Answers

MyObject my_object = MyObject(0);

This line creates my_object on the stack using MyObject's constructor that can accept an int.

my_object = MyObject(1);

This line creates a temporary MyObject, again, using the same constructor as the first. This is then assigned to my_object by calling the assignment operator. If you didn't provide this operator then the compiler will make one for you that performs a shallow copy. When this statement completes, the temporary MyObject goes out of scope and the destructor for it is called.

When your my_object goes out of scope it is in turn destroyed in the same fashion. At no point do you need to manually delete this because everything is allocated on the stack.

like image 190
greatwolf Avatar answered Sep 22 '22 00:09

greatwolf


There are two main regions in memory when talking about newly created objects: the stack and the heap. The heap contains all objects created dynamically with new. These objects need to be explicitly deleted with the delete operator. The stack is scope-specific and all objects defined on the stack will be deleted automatically. Since you don't use new, all your objects will be destroyed when their scope ends.

Assuming no compiler optimizations, your code roughly translates to:

{
   MyObject my_object;
   MyObject tempObject0(0);
   my_Object = tempObject0;
   MyObject tempObject1(1);
   my_Object = tempObject;
}//3 objects are deleted by this point (in theory)

Also note the difference between

MyObject myObject(0);

and

MyObject myObject = MyObject(0);

The second case creates a temporary object, so it will be less efficient. This all of course assuming no optimizations. Depending on the compiler, it might translate to the same thing.

like image 21
Luchian Grigore Avatar answered Sep 22 '22 00:09

Luchian Grigore