C ++ Copy constructor called here?

Suppose you have the following functions:

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 function returns, is the copy constructor called (suppose it will be one)?

+5
source share
3 answers

It can be called, or it cannot be called. The compiler has the ability to use Return Value Optimization in both cases (although optimization is a bit easier in barthan in foo).

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

+10
source

" " .

+8

It can be called. It can also be optimized. See some other questions in the same direction.

+2
source

All Articles