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

后端 未结 7 476
灰色年华
灰色年华 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:05

    There is a pretty good chance that a peephole optimizer will catch this. Many (most?) compilers implement one, so the answer is probably "yes".

    As others have notes this is not a trivial question at the AST rewriting level.


    Peephole optimizers work on a representation of the code at a level equivalent to assembly language (but before generation of actual machine code). There is a chance to notice the load of the return value into a register followed by a overwrite with no intermediate read, and just remove the load. This is done on a case by case basis.

提交回复
热议问题