简体   繁体   中英

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

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.

取决于是否应用返回值优化

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM