سؤال

I have the following code:

#include <iostream>
using namespace std;

class X
{
public:
    int g;
    X() { cout << "constr" << endl; }
    X(const X& ref1) { cout << "copy constr" << endl; }
};

X f()
{
    X ee;
    ee.g = 1;
    return ee;
}

int main()
{
    X ff = f();
    return 0;
}

Running the code I see that the constructor was called only once and the copy constructor was never called. Don't you expect two constructor and one copy constructor calls here? Thanks!

هل كانت مفيدة؟

المحلول

This is a special case of the copy elision called return value optimization (the link explains precisely your case).

نصائح أخرى

Copy Elision is an optimization implemented by many compilers to prevent extra, unnecessary, copies. Makes the return-by-value or pass-by-value possible in practice.

Take a look at the example in the following answer: https://stackoverflow.com/a/12953129/1938163

struct C {
  C() {}
  C(const C&) { std::cout << "A copy was made.\n"; }
};

C f() {
  return C();
}

int main() {
  std::cout << "Hello World!\n";
  C obj = f();
}

(http://en.wikipedia.org/wiki/Return_value_optimization#Summary)

Perhaps incredible to believe the first time, depending on the compiler & settings, the following outputs are all valid:

Hello World! 
A copy was made. 
A copy was made. 

Hello World! 
A copy was made.

Hello World!

In your case, this is a special copy elision optimization called RVO - Return Value Optimization where an object returned by value from a method has its copy elided.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top