Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Is the copy constructor called here?

Suppose you have a functions like this:

Foo foo() {
  Foo foo;

  // more lines of code

  return foo; // is the copy constructor called here?
}

Foo bar() {
  // more lines of code

  return Foo(); // is the copy constructor called here?
}

int main() {
  Foo a = foo();
  Foo b = bar();  
}

When any of the functions return, is the copy constructor called (suppose there would be one)?

like image 339
helpermethod Avatar asked Mar 02 '11 21:03

helpermethod


3 Answers

It might be called, or it might not be called. The compiler has the option of using the Return Value Optimization in both cases (though the optimization is a bit easier in bar than in foo).

Even if RVO eliminates the actual calls to the copy constructor, the copy constructor must still be defined and accessible.

like image 89
aschepler Avatar answered Nov 08 '22 11:11

aschepler


Depends on the Return Value Optimization being applied or not.

like image 35
Nikolai Fetissov Avatar answered Nov 08 '22 12:11

Nikolai Fetissov


It may be called. It also may be optimized away. See some other question in the same direction.

like image 2
xtofl Avatar answered Nov 08 '22 11:11

xtofl