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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With