Should accessors return values or constant references?

后端 未结 8 1263
谎友^
谎友^ 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:41

    One of the goals of having an accessor method is to try, at least to some extent, to abstract your class implementation from its interface.

    Returning by value is better because there are no lifetime issues with the referenced object. Should you decide not to have a std::string member but, say, a std::stringstream or to create a std::string on the fly you don't have to change the interface.

    Returning by const reference isn't the opposite of taking a parameter by const reference, taking a value by const reference doesn't tie your internal data representation to the external interface.

提交回复
热议问题