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?