Should accessors return values or constant references?

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

    Generally you should return PODs by value (e.g, int, short, char, long etc,) and a const reference for more complex types:

    int getData() const;
    short getMoreData() const;
    const std::string& getName() const;
    const ComplexObject& getComplexData() const;
    

提交回复
热议问题