Understanding return value optimization and returning temporaries - C++

后端 未结 4 1600
再見小時候
再見小時候 2020-11-28 07:26

Please consider the three functions.

std::string get_a_string()
{
    return \"hello\";
}

std::string get_a_string1()
{
    return std::string(\"hello\");
}         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 07:55

    1. It depends on your compiler - what platform are you referring to? Best way to find out is to compile a very small test app and check the ASM your compiler produces.

    2. Yes, it is OK, although you never mention what you're concerned about; speed? style? you can a local temporary to a const reference - the lifetime of the temporary will be extended to the lifetime of the reference - try it and see for yourself! (Herb Sutter exaplins this here) See end of post for example.

    IMO you're almost always better off trusting your compiler to optimise your code for you. There are very few cases where you should need to care about this sort of thing (very low level code is one such area, where you're interactive with hardware registers).

    int foo() { return 42; }
    
    int main(int, char**)
    {
        const int &iRef = foo();
        // iRef is valid at this point too!
    }
    

提交回复
热议问题