C++是否在此处调用了复制构造函数?

hel*_*hod 5 c++ copy-constructor

假设你有这样的函数:

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();  
}
Run Code Online (Sandbox Code Playgroud)

当任何函数返回时,是否调用了复制构造函数(假设会有一个)?

asc*_*ler 10

它可能被调用,或者可能不会被调用.在两种情况下,编译器都可以选择使用返回值优化(尽管优化bar比in 更容易foo).

即使RVO消除了对复制构造函数的实际调用,仍必须定义和访问复制构造函数.


Nik*_*sov 8

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