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

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

    The only problem I have with returning a const-reference, which is something I would typically do for non basic types, is that there is nothing to stop the caller removing the "const"ness and then modifying the value.

    Personally, I'd suggest that such code is a bug. If they know you're returning a reference and continue to cast away the const then it's on their head.

提交回复
热议问题