best way to return an std::string that local to a function

前端 未结 6 845
陌清茗
陌清茗 2021-01-30 16:07

In C++ what is the best way to return a function local std::string variable from the function?

std::string MyFunc()
{
    std::string mystring(\"test\");
    ret         


        
6条回答
  •  别跟我提以往
    2021-01-30 16:41

    As mentioned, the std::string is copied. So even the original local variable has gone out of scope, the caller gets a copy of the std::string.

    I think reading on RVO can totally clear your confusion. In this case, it's accurately referred to as NRVO (Named RVO) but the spirit is the same.

    Bonus reading: The problem with using RVO is that it's not the most flexible thing in the world. One of the big buzzes of C++0x is rvalue references which intends to solve that problem.

提交回复
热议问题