Why did I get two temporary objects when returning an object from a function

This is my C ++ code

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; } 

I found that there are two temporary objects, looking at the assembly code

 //in main CTest obj = Return(10); 0009F6CE push 0Ah 0009F6D0 lea eax,[ebp-158h] ; pass the first temporary object 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] 

Why did I get the second temporary object. It seems that only one temporary object is enough. If I add an empty destructor, ~CTest() {} will not have a temporary object (RVO?).

+4
source share
1 answer

"Why did I get the second temporary object"

Probably because you turned off optimization.

Otherwise, the compiler will perform the optimization by passing obj from the main as a hidden parameter (just like the this pointer) to the Return function and assign it the result.

So, after optimization, your code will look like this:

 void Return(void* put_result_here , int val) { CTest obj; obj.number = val; put_result_here = obj; } int main() { CTest obj; Return(&obj , 10); return 0; } 

This optimization is called returns value optimization .

0
source

Source: https://habr.com/ru/post/1493905/


All Articles