What is the best way to return string in C++?

后端 未结 7 1076
刺人心
刺人心 2020-12-04 15:16

My question is simple: if I have some class Man and I want to define member function that returns man\'s name, which of the following two variants shall I prefer?

Fi

相关标签:
7条回答
  • 2020-12-04 15:54

    use the first variant:

    string name();
    

    The compiler will most likely optimize out any unnecessary copies. See return value optimization.

    In C++11, move semantics means that you don't perform a full copy even if the compiler doesn't perform RVO. See move semantics.

    Also bear in mind that if the alternative is

    void name(std::string& s);
    

    then you have to specify very clearly what can happen to s and what values it can have when passed to the function, and probably either do a lot of validity checking, or simply overwrite the input entirely.

    0 讨论(0)
提交回复
热议问题