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

前端 未结 8 1499
暗喜
暗喜 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:36

    My rule of thumb is to return a copy for simple basic datatypes such as int, string etc. For a bit more complicated structures where copying may be costlier (like vector you mentioned) I prefer to return a const-reference.

提交回复
热议问题