gpt4 book ai didi

C++ 复制构造函数、临时对象和复制语义

转载 作者:IT老高 更新时间:2023-10-28 22:13:40 24 4
gpt4 key购买 nike

对于这个程序

#include <iostream>
using std::cout;

struct C
{
C() { cout << "Default C called!\n"; }
C(const C &rhs) { cout << "CC called!\n"; }
};

const C f()
{
cout << "Entered f()!\n";
return C();
}

int main()
{
C a = f();
C b = a;

return 0;
}

我得到的输出是:

Entered f()!
Default C called!
CC called!

由于 f() 是按值返回的,它应该返回一个临时值。既然T a = x;就是T a(x);,那它不会调用复制构造函数来构造a吗?临时传入的参数?

最佳答案

Since f() is returning by value, it should return a temporary. As T a = x; is T a(x);, wouldn't it call the copy constructor for the construction of a, with the temporary passed-in as its argument?

查找返回值优化。这是默认开启的。如果您在 Windows 上使用 MSVC 2005+,您可以使用 /Od 将其关闭并获得所需的结果(或 GCC 上的 -fno-elide-constructors)。此外,对于 MSVC,请参阅 this文章。

12.8 Copying class objects

15 When certain criteria are met, animplementation is allowed to omit thecopy construction of a class object,even if the copy constructor and/ordestructor for the object have sideeffects. In such cases, theimplementation treats the source andtarget of the omitted copy operationas simply two different ways ofreferring to the same object, and thedestruction of that object occurs atthe later of the times when the twoobjects would havebeen destroyed without theoptimization.115 This elision of copyoperations is permitted in thefollowing circumstances (which may becombined to eliminate multiplecopies):

in a return statement in afunction with a class return type,when the expression is the name of anon-volatile automatic object with thesame cv-unqualified type as thefunction return type, the copyoperation can be omitted byconstructing the automatic objectdirectly into the function’s returnvalue— in a throw-expression, whenthe operand is the name of anon-volatile automatic object, thecopy operation from the operand to theexception object (15.1) can be omittedby constructing the automatic objectdirectly into the exception object

—when a temporary class object that hasnot been bound to a reference (12.2)would be copied to a class object withthe same cv-unqualified type, the copyoperation can be omitted byconstructing the temporary objectdirectly into the target of theomitted copy

— when theexception-declaration of an exceptionhandler (Clause 15) declares an objectof the same type (except forcv-qualification) as the exceptionobject (15.1), the copy operation canbe omitted by treating theexception-declaration as an alias forthe exception object if the meaning ofthe program will be unchanged exceptfor the execution of constructors anddestructors for the object declared bythe exception-declaration.

Note: Emphasis mine

关于C++ 复制构造函数、临时对象和复制语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2323225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com