Why does a custom constructor affect the generated assembly?

test environment: vs 2008, debug mode

test code:

// a demo for return value class C { public: int value; int value2; int value3; //C(int v=0): value(v) {}; }; C getC(int v) { C c1; return c1; } int main() { C c1 = getC(10); return 0; } 

and asm output:

 ; 39 : C c1 = getC(10); push 10 ; 0000000aH lea eax, DWORD PTR $T2595[ebp] push eax call ?getC@ @ YA?AVC@ @ H@Z ; getC add esp, 8 mov ecx, DWORD PTR [eax] mov DWORD PTR $T2594[ebp], ecx mov edx, DWORD PTR [eax+4] mov DWORD PTR $T2594[ebp+4], edx mov eax, DWORD PTR [eax+8] mov DWORD PTR $T2594[ebp+8], eax mov ecx, DWORD PTR $T2594[ebp] mov DWORD PTR _c1$[ebp], ecx mov edx, DWORD PTR $T2594[ebp+4] mov DWORD PTR _c1$[ebp+4], edx mov eax, DWORD PTR $T2594[ebp+8] mov DWORD PTR _c1$[ebp+8], eax 

From the output of asm, we see that compilation creates 2 temporary objects.

However, when I define the constructor as follows:

 C(int v=0): value(v) {}; 

and recompile the program, asm output will be:

 ; 39 : C c1 = getC(10); push 10 ; 0000000aH lea eax, DWORD PTR _c1$[ebp] push eax call ?getC@ @ YA?AVC@ @ H@Z ; getC add esp, 8 

Obviously, the compiler optimizes the code, and my question is:

Why does adding a user-written constructor affect the generated assembly?

+7
source share
1 answer

This question is about copy optimization and return value optimization in C ++.

I suggest you not to spend a lot of time on this, because the generated assembly code depends on the compiler.

Copying elision is defined in the standard:

When certain criteria are met, the implementation allows you to omit the copy / move construct of the class object, even if the copy / move constructor and / or destructor for the object have side effects. In such cases, the implementation considers the source and purpose of the missed copy / move operation as just two different ways of accessing the same object, and the destruction of this object occurs in later times, when these two objects would be destroyed without optimization. This exclusion of copy / move operations, called copying, is allowed in the following cases (which can be combined to eliminate multiple copies):

[...]

ยง12.8 [class.copy]

There is already a question that you can refer to stackoverflow for, see here .

+1
source

All Articles