可能重复:
Understanding return value optimization and returning temporaries - C++
让Integer是一个类,i作为它的成员。left和right作为参数传递给函数调用,并且是Integer类型的。
现在就像布鲁斯·艾克尔所说的那样。
代码1:
return Integer(left.i+right.i);代码2:
Integer tmp(left.i+right.i);
return tmp;代码1要求创建一个临时整数对象并返回它,这与创建一个命名局部变量并返回它是不同的,这是一个普遍的误解。
在代码1中(称为返回临时方法):
编译器知道您不需要它所创建的对象,然后返回it.The编译器利用building the object directly into the location of the outside return value的优势。这只需要一个普通的构造函数调用(不需要复制构造函数),也不需要析构函数,因为没有创建本地对象。
而代码2中将出现3种情况:
( a)创建了tmp对象,包括它的构造函数调用
b) the copy-constructor copies the tmp to the location of the outside return value。
( c)在作用域结束时调用析构函数tmp。
在代码1中,这意味着什么:building the object directly into the location of the outside return value?
另外,为什么代码1中不调用复制构造函数?
另外,我不明白代码2中的步骤b在做什么?即the copy-constructor copies the tmp to the location of the outside return value.
发布于 2012-01-04 08:31:13
编译器可以自由地为、按值传递的和优化复制构造函数。我的猜测是,任何合适的优化器都会为这两个变体生成相同的二进制。
代码的优化版本:
A foo()
{
A temp;
00401000 mov ecx,dword ptr [A::x (40337Ch)]
00401006 mov dword ptr [eax],ecx
00401008 add ecx,1
0040100B mov dword ptr [A::x (40337Ch)],ecx
return temp;
}所以您可以看到,复制构造函数没有被调用,即使在我的版本中,它有一个cout,所以它确实会影响观察到的行为。
没有优化:
A foo()
{
004113C0 push ebp
004113C1 mov ebp,esp
004113C3 sub esp,0CCh
004113C9 push ebx
004113CA push esi
004113CB push edi
004113CC lea edi,[ebp-0CCh]
004113D2 mov ecx,33h
004113D7 mov eax,0CCCCCCCCh
004113DC rep stos dword ptr es:[edi]
A temp;
004113DE lea ecx,[temp]
004113E1 call A::A (4110E6h)
return temp;
004113E6 lea eax,[temp]
004113E9 push eax
004113EA mov ecx,dword ptr [ebp+8]
/// copy constructor called on next line:
004113ED call A::A (411177h)
004113F2 mov eax,dword ptr [ebp+8]
}短语"b)复制构造函数将tmp复制到外部返回值的位置。“很严重,有时甚至都不会发生。
应该记住的是,您不应该依赖于调用复制构造函数。
https://stackoverflow.com/questions/8723916
复制相似问题