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

前端 未结 6 655
陌清茗
陌清茗 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:40

    There will be a problem if your code is like:

    std::string& MyFunc()
    {
        std::string mystring("test");
        return mystring;
    }
    

    So, the way you've written it is OK. Just one advice - if you can construct the string like this, I mean - you can do it in one row, it's sometimes better to do it like this:

    std::string MyFunc()
    {
        return "test";
    }
    

    Or if it's more "complicated", for ex:

    std::string MyFunct( const std::string& s1, 
                         const std::string& s2, 
                         const char* szOtherString )
    {
        return std::string( "test1" ) + s1 + std::string( szOtherString ) + s2;
    }
    

    This will give a hint to your compiler to do more optimization, so it could do one less copy of your string (RVO).

提交回复
热议问题