在getter函数中返回一个const引用或副本? [英] Return a const reference or a copy in a getter function?

查看:137
本文介绍了在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)可以更快,但不必因为RVO。

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(什么字?)的更改吗?然后你需要传回一个引用。

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引用或副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆