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

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

    I'm returning a reference, because a string seems not "cheap to copy" to me. It's a complex data type with dynamic memory management and all that.

    The "if you want the caller to get a copy, you should return by value" argument is moot, because it doesn't preclude copies at all. The caller can still do the following and get a copy anyway

    string s = obj.str();
    

    You need to explicitly create a reference on the caller side to be able to refer to the data member directly afterwards - but why would you do that? There definitely are enough user defined types that are cheap to copy

    • Smart Pointers
    • Iterators
    • All of the non-class types.

提交回复
热议问题