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中是否说最好按值返回,因为多个副本将被优化?还是我对他的理解有误?
按价值。
我在野外遇到过类似的代码:
A foo();
std::string const& x = foo().test_by_const_ref();
Run Code Online (Sandbox Code Playgroud)
Boom,x是一个悬空的参考。
按价值回报则不会发生这种情况。
| 归档时间: |
|
| 查看次数: |
8109 次 |
| 最近记录: |