Understanding return value optimization and returning temporaries - C++

后端 未结 4 1595
再見小時候
再見小時候 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:33

    First, it's completely okay to return a temporary by value which is what you do. It is copied and though the original will go out of scope the copy will not do so and can be safely used by the caller.

    Second, all three cases are in fact identical (since you don't access the temporary in the third case anyway) and a compiler might even emit the same code for all of them. Hence it can use RVO in all three cases. This is entirely compiler-dependent.

提交回复
热议问题