复制伊利森误会


#include <iostream>
struct A
{
    A() { std::cout << "Def Constrn"; }
    A(const A&) { std::cout << "Copy Constrn"; }
};
A func1() 
{
    return A{};
}
void func2(A a) {}
int main()
{
    func2(func1());
}

编译后

g++ Copy.cpp -std=c++11 -fno-elide-constructors

输出为 :

Def Constr

复制康斯特

复制康斯特

我的问题是:为什么是 2 个副本?我以为只需要 1 份副本。

我可能猜测func1((抛出了一个临时对象,并且需要将这个临时对象复制到另一个内存区域,并且必须再次从该区域为func2((参数复制,但这对我来说很模糊。

你能详细解释一下吗?

  1. func1 的返回值是从表达式 A{} 复制的。
  2. 函数调用表达式func1()的值被复制到 func2 的函数参数中。

是的,你的理解是对的。您的代码行(不带复制省略(类似于

int main()
{
  {
    A temp = func1();  // 2nd copy
    func2(temp);  // 3rd copy
  }
}

最新更新