这是我的 C++ 代码
class CTest {
public:
int number;
int arr[10];
};
CTest Return(int val) {
CTest obj;
obj.number = val;
return obj;
}
int main() {
CTest obj = Return(10);
return 0;
}
我通过查看汇编代码发现有两个临时对象
//in main
CTest obj = Return(10);
0009F6CE push 0Ah
0009F6D0 lea eax,[ebp-158h] ; pass the first temporary object's address to Return
0009F6D6 push eax
0009F6D7 call Return (0822E9h)
0009F6DC add esp,8
0009F6DF mov ecx,0Bh
0009F6E4 mov esi,eax
0009F6E6 lea edi,[ebp-124h] ; copy from the first temporary object
0009F6EC rep movs dword ptr es:[edi],dword ptr [esi]
0009F6EE mov ecx,0Bh
0009F6F3 lea esi,[ebp-124h]
0009F6F9 lea edi,[obj] ; copy from the second temporary object
0009F6FC rep movs dword ptr es:[edi],dword ptr [esi]
//in Return
CTest obj;
obj.number = val;
0009F64E mov eax,dword ptr [val]
0009F651 mov dword ptr [obj],eax
return obj;
0009F654 mov ecx,0Bh
0009F659 lea esi,[obj]
0009F65C mov edi,dword ptr [ebp+8]
0009F65F rep movs dword ptr es:[edi],dword ptr [esi] ; copy to the first temporary object
0009F661 mov eax,dword ptr [ebp+8]
为什么我得到了第二个临时对象。似乎只有一个临时对象就足够了。如果我添加一个空的析构函数~CTest() {}
将没有临时对象(RVO?)。