compiler optimization

前端 未结 4 531
耶瑟儿~
耶瑟儿~ 2021-02-05 23:01

So I have a question for you. :) Can you tell me the output the following code should produce?

#include 
struct Optimized
{
    Optimized() { std         


        
4条回答
  •  自闭症患者
    2021-02-05 23:44

    This is known as Copy Elision and is a special handling instead of copying/moving.

    The optimization is specifically allowed by the Standard, as long as it would be possible to copy/move (ie, the method is declared and accessible).

    The implementation in a compiler is generally referred to, in this case, as Return Value Optimization. There are two variations:

    • RVO: when you return a temporary (return "aa" + someString;)
    • NRVO: N for Named, when you return an object that has a name

    Both are implemented by major compilers, but the latter may kick in only at higher optimization levels as it is more difficult to detect.

    Therefore, to answer your question about returning structs: I would recommend it. Consider:

    // Bad
    Foo foo;
    bar(foo);
    
    -- foo can be modified here
    
    
    // Good
    Foo const foo = bar();
    

    The latter is not only clearer, it also allows const enforcement!

提交回复
热议问题