Returning a const reference to an object instead of a copy

前端 未结 12 609
天命终不由人
天命终不由人 2020-11-29 16:40

Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:

class foo
{
private:
    std::st         


        
12条回答
  •  悲&欢浪女
    2020-11-29 17:32

    Depends what you need to do. Maybe you want to all the caller to change the returned value without changing the class. If you return the const reference that won't fly.

    Of course, the next argument is that the caller could then make their own copy. But if you know how the function will be used and know that happens anyway, then maybe doing this saves you a step later in code.

提交回复
热议问题