哪个更好:按值或按常量引用返回std::string

What is better: return std::string by value or by constant reference?

本文关键字:返回 引用 常量 std string 更好      更新时间:2023-10-16

这个类有两个不同返回类型的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; }
};
// ...

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

按值。

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

A foo();
std::string const& x = foo().test_by_const_ref();

哎呀,x是一个悬空引用。

按值返回不会发生这种情况

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

按值返回,因为编译器会优化返回值