0

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?

Takayuki Sato
  • 1,023
  • 1
  • 14
  • 22
  • 3
    It is a [return value optimization](http://en.wikipedia.org/wiki/Return_value_optimization) – myaut Apr 14 '15 at 09:25
  • Also, http://stackoverflow.com/questions/4986673/c11-rvalues-and-move-semantics-confusion-return-statement for the "implicit move" part. – T.C. Apr 14 '15 at 09:26

0 Answers0