Lifetime extension and the conditional operator

前端 未结 2 766
梦如初夏
梦如初夏 2020-12-31 01:22

local lvalue references-to-const and rvalue references can extend the lifetime of temporaries:

const std::string& a = std::string(\"hello\");
std::string         


        
2条回答
  •  离开以前
    2020-12-31 02:01

    std::string d = "hello";
    const std::string& e = condition ? d : std::string("world");
    

    Does C++ mandate the lifetime of the temporary be extended when the condition is false?

    It will be. The conditional is an rvalue expression, and when bound with a const reference the compiler will create an unnamed object and bind the reference to it. What I am not 100% sure is whether the temporary whose lifetime is extended is std::string("world") or whether a copy of it is (conceptually) made (and elided).

提交回复
热议问题