Will the c++ compiler optimize away unused return value?

后端 未结 7 482
灰色年华
灰色年华 2021-01-18 19:24

If I have a function that returns an object, but this return value is never used by the caller, will the compiler optimize away the copy? (Possibly an always/sometimes/never

相关标签:
7条回答
  • 2021-01-18 20:08

    If return value is an int and you return 0 (as in the edited question), then this may get optimized away.

    You have to look at the underlying assembly. If the function is not inlined then the underlying assembly will execute a mov eax, 0 (or xor eax, eax) to set eax (which is usually used for integer return values) to 0. If the function is inlined, this will certainly get optimized away.

    But this senario isn't too useful if you're worried about what happens when you return objects larger than 32-bits. You'll need to refer to the answers to the unedit question, which paint a pretty good picture: If everything is inlined then most of it will be optimized out. If it is not inlined, then the functions must be called even if they don't really do anything, and that includes the constructor of an object (since the compiler doesn't know whether the constructor modified global variables or did something else weird).

    0 讨论(0)
提交回复
热议问题