哪个更好:按值或按常量引用返回std::string
What is better: return std::string by value or by constant reference?
这个类有两个不同返回类型的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将在幕后负责返回引用,因此您的代码将具有完美的语义和干净。
按值返回,因为编译器会优化返回值
相关文章:
- 寿命延长从函数返回引用
- 了解C++如何返回引用并绑定到引用
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 从类返回引用向量
- 使用unique_ptr并返回引用,或者我应该使用shared_ptr并在需要时制作副本
- 混淆C++从函数返回引用
- 两个相同的重载运算符[]一个返回引用
- 为什么向量的.at()成员函数返回引用而不是迭代器
- C++使用和返回引用
- 返回 T 引用的 Const 函子禁止赋值
- 返回引用是否也会延长其生存期?
- 如何返回引用,然后递增迭代器
- 如果使用返回引用的函数初始化"auto"var,为什么它不声明引用类型?
- 我是否需要将 ref 与 make_pair 一起使用才能返回引用?
- 在 vector::at 返回引用后进行更改
- 为什么PyImport_ImportModule返回引用计数为 3 而不是 1 的 PyObject*
- 超出返回引用的单一实例生存期
- Boost.Python 返回引用现有 c++ 对象的 python 对象
- C++ 运算符 += 重载返回引用
- 如何声明接受转发引用并返回引用或副本的函数模板