在 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).
相关文章