Return a const reference or a copy in a getter function?(在 getter 函数中返回 const 引用或副本?)
问题描述
默认情况下,从 getter 函数返回副本 (1) 或引用 (2) 更好?
What's better as default, to return a copy (1) or a reference (2) from a getter function?
class foo {
public:
std::string str () { // (1)
return str_;
}
const std::string& str () { // (2)
return str_;
}
private:
std::string str_;
};
我知道 2) 可能会更快,但由于 (N)RVO 而不必如此.1) 对于悬空引用更安全,但对象可能会过期或永远不会存储引用.
I know 2) could be faster but don't have to due to (N)RVO. 1) is safer concerning dangling references but the object will probably outlife or the reference is never stored.
当您编写课程但(尚)不知道性能和生命周期问题是否重要时,您的默认设置是什么?
What's your default when you write a class and don't know (yet) whether performance and lifetime issues matter?
附加问题:当成员不是纯字符串而是向量时,游戏是否会改变?
Additional question: Does the game change when the member is not a plain string but rather a vector?
推荐答案
这真的取决于你对 默认行为 的期望.
Well it really depends on what you expect the behaviour to be, by default.
您是否希望调用者看到对他们的 str_unbeknownst(真是一个词!)所做的更改?然后你需要传回一个参考.如果您可以拥有一个 refcounted 数据成员并将其返回,那可能会很好.
Do you expect the caller to see changes made to str_ unbeknownst(what a word!) to them? Then you need to pass back a reference. Might be good if you can have a refcounted data member and return that.
如果您希望调用者得到一份副本,请执行 1).
If you expect the caller to get a copy, do 1).
这篇关于在 getter 函数中返回 const 引用或副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 getter 函数中返回 const 引用或副本?


基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01