views:

310

answers:

2

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?

+16  A: 

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

Konrad Rudolph
+1  A: 

Out of curiosity: why

MyClass obj = MyClass();

and not simply

MyClass obj;
Nemanja Trifunovic
I would guess it's because he is used to programming in java...
Evan Teran
Yes, it's because of a lot programming in Java before :)
artknish