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

后端 未结 7 477
灰色年华
灰色年华 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 19:46

    just tried this example on compiler explorer, and at -O3 the mov is not generated when the return value is not used.

    https://gcc.godbolt.org/z/v5WGPr

    0 讨论(0)
  • 2021-01-18 19:52

    I doubt most compilers could do that if they were in different compilation objects (ie. different files). Maybe if they were both in the same file, they could.

    0 讨论(0)
  • 2021-01-18 19:58

    They most likely will if the optimization level causes them to inline the code. If not, they would have to generate two different translations of the same code to make it work, which could open up a lot of edge case problems.

    0 讨论(0)
  • 2021-01-18 20:03

    The linker can take care of this sort of thing, even if the original caller and called are in different compilation units.

    If you have a good reason to be concerned about the CPU load dedicated to a method call (premature optimization is the root of all evil,) you might consider the many inlining options available to you, including (gasp!) a macro.

    Do you REALLY need to optimize at this level?

    0 讨论(0)
  • 2021-01-18 20:05

    If the ReturnValue class has a non-trivial copy constructor, the compiler must not eliminate the call to the copy constructor - it is mandated by the language that it is invoked.

    If the copy constructor is inline, the compiler might be able to inline the call, which in turn might cause a elimination of much of its code (also depending on whether FunctionThatAltersMembersAndNeverFails is inline).

    0 讨论(0)
  • 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.

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