复制构造函数?

Joh*_*ohn 3 c++

可能重复:
为什么在这种情况下不调用复制构造函数?

通过值将对象传递给函数或按值从函数返回对象时,必须调用复制构造函数.但是,在某些编译器中,这不会发生?任何解释?

Dou*_* T. 5

我假设它们指的是在许多编译器中实现的返回值优化,其中代码:

CThing DoSomething();
Run Code Online (Sandbox Code Playgroud)

变成了

void DoSomething(CThing& thing);
Run Code Online (Sandbox Code Playgroud)

将事物在堆栈上声明并传递给DoSomething:

CThing thing;
DoSomething(thing);
Run Code Online (Sandbox Code Playgroud)

这可以防止需要复制CThing.


Pet*_*der 5

它通常不会发生,因为它不需要发生.这称为复制省略.在许多情况下,该函数不需要复制,因此编译器会将它们优化掉.例如,使用以下功能:

big_type foo(big_type bar)
{
  return bar + 1;
}

big_type a = foo(b);
Run Code Online (Sandbox Code Playgroud)

将转换为类似的东西:

void foo(const big_type& bar, big_type& out)
{
  out = bar + 1;
}

big_type a;
foo(b, a);
Run Code Online (Sandbox Code Playgroud)

删除返回值称为"返回值优化"(RVO),并且由大多数编译器实现,即使关闭优化也是如此!