Should accessors return values or constant references?

后端 未结 8 1284
谎友^
谎友^ 2020-12-05 08:17

Suppose I have a class Foo with a std::string member str. What should get_str return?

std::string Foo::ge         


        
8条回答
  •  长情又很酷
    2020-12-05 08:46

    It depends on what you want to do with the return value.

    This is better if you just want to make a query and not modify str.

    const std::string& Foo::get_str() const
    {
        return str;
    }
    

    Otherwise, go for this:

    std::string& Foo::get_str()
    {
        return str;
    }
    

    And if you want a copy/clone of str, then use this:

    std::string Foo::get_str() const
    {
        return str;
    }
    

提交回复
热议问题