Return a const reference or a copy in a getter function?

前端 未结 8 1500
暗喜
暗喜 2020-12-12 20:50

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)
              


        
8条回答
  •  孤街浪徒
    2020-12-12 21:21

    Well it really depends on what you expect the behaviour to be, by default.

    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.

    If you expect the caller to get a copy, do 1).

提交回复
热议问题