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

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

    1. if its a small basic type - primatives like int and long and their wrappers and other basic things like 'Point' - return a copy

    2. if its a string, or any other complex type - return a reference.

提交回复
热议问题