Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the destructor not called for the returned object from the function?

I was thinking that when a function returns an object on the stack to the calling function, the calling function gets a copy of the original object but the original object's destructor is called as soon as the stack unwinds. But in the following program, the destructor is getting called only once. I expected it to be called twice.

#include <iostream>

class MyClass
{
public:
  ~MyClass() { std::cout << "destructor of MyClass" << std::endl; }
};

MyClass getMyClass()
{
  MyClass obj = MyClass();
  return obj;   // dtor call for obj here?
}

int main()
{
  MyClass myobj = getMyClass();
  return 0;  // Another dtor call for myobj.
}

But "destructor of MyClass" is getting printed only once. Is my assumption wrong or is there something else going on here?

like image 858
Srikanth Avatar asked Mar 30 '09 16:03

Srikanth


People also ask

Why is my destructor not called?

There are two reasons that your destructors aren't being called, one is as kishor8dm pointed out that you are using the operator "new" and because of that the "delete" command must be called explicitly.

Is destructor called before return?

While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function.

What happens to destructor when an object is passed by reference?

Explanation: The destructor is never called in this situation. The concept is that when an object is passed by reference to the function, the constructor is not called, but only the main object will be used. Hence no destructor will be called at end of function.

Why destructor does not take any argument?

The destructor does not have arguments. It has no return type not even void. An object of a class with a Destructor cannot become a member of the union. A destructor should be declared in the public section of the class.


1 Answers

This is a special case where the compiler is allowed to optimize out the copy: this is called named return value optimization (NRVO). Basically, the compiler allocates memory for the return object on the call site and lets the function fill in that memory directly instead of creating the object at the called site and copying it back. Modern compilers do this routinely whenever possible (there are some situations where this isn't easy since there are several return paths in the function that return different instances).

like image 79
Konrad Rudolph Avatar answered Oct 26 '22 08:10

Konrad Rudolph