哪个更好:按值返回 std::string 还是按常量引用返回?

vla*_*don 2 c++ return-type return-by-reference c++11 return-by-value

这是一个具有两个不同返回类型的 getter 的类:

class A {
    std::string m_test { "test" };

public:
    std::string test_by_value { return m_test; }
    const std::string& test_by_const_ref() { return m_test; }
};

// ...
Run Code Online (Sandbox Code Playgroud)

哪个更好?它是关于 std::string 的,而不是内置类型。STL在https://channel9.msdn.com/Events/GoingNative/2013/Don-t-Help-the-Compiler中是否说最好按值返回,因为多个副本将被优化?还是我对他的理解有误?

Max*_*kin 5

按价值。

我在野外遇到过类似的代码:

A foo();

std::string const& x = foo().test_by_const_ref();
Run Code Online (Sandbox Code Playgroud)

Boom,x是一个悬空的参考。

按价值回报则不会发生这种情况。


Bli*_*ndy 5

链接正确,string按值返回对象。NRVO将负责返回引用,而不是在幕后,因此您的代码将具有完美的语义和干净的结果。