#include <iostream>
using namespace std;
class ClassA {
int k;
public:
ClassA(int i) : k(i)
{
}
~ClassA()
{
cout << "A destroyed" << " k=" << k << endl;
}
ClassA copyAndModify()
{
ClassA a(k*2);
return a;
}
void taunt()
{
cout << k << endl;
}
};
int main (int argc, char * const argv[]) {
ClassA original(1)
ClassA modified = original.copyAndModify();
modified.taunt();
return 0;
}
I thought that the object ‘a’ (inside method copyAndModify) was deconstructed when the method returned, but it didn’t. Does this mean all objects, created inside a method, that are being returned don’t get deconstructed? Is this true for all compilers?
You have encountered the Return Value Optimization. No, it is not going to be the same on all compilers.