Question

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?

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top