5

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)?

helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • 2
    What do you mean by "suppose there would be one"? Every class has a copy constructor (though it may be `private`, or in C++0x `delete`d). If the class doesn't declare one, it gets an implicitly-declared copy constructor. – aschepler Mar 02 '11 at 21:07
  • Also see http://stackoverflow.com/questions/665825/copy-constructor-vs-return-value-optimization – xtofl Mar 02 '11 at 21:07
  • 2
    It's easy to test something like this. Just implement a copy constructor and print a message in it. – gregg Mar 02 '11 at 21:15

3 Answers3

10

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.

aschepler
  • 70,891
  • 9
  • 107
  • 161
8

Depends on the Return Value Optimization being applied or not.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
2

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

Community
  • 1
  • 1
xtofl
  • 40,723
  • 12
  • 105
  • 192