I tried following code, but the result was unexpected one.
#include <string>
#include <iostream>
#include <string>
using namespace std;
class A {
public:
string s;
A(string x) : s(x) { cout << "A:" << s << endl; }
A(const A&& x) : s(x.s) { cout << "Am:" << s << endl; }
A(const A& x) : s(x.s) { cout << "Ac:" << s << endl; }
~A() { cout << "~A: " << s << endl; }
};
A f(A& a) {
A r(a.s + "'");
return r;
}
int main(int argc, char *argv[]) {
A a("1");
A b(f(a));
cout << b.s << endl;
return 0;
}
The result was,
$ c++ -g -std=c++0x /home/takayuki/tmp/x.cpp && ./a.out
A:1
A:1'
1'
~A: 1'
~A: 1
In my understanding, constructor and destructor should be called 3 times each, because f
creates local variable, but the result doesn't.
Is this kind of compiler optimization? Or something wrong with my understanding?