Should accessors return values or constant references?

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

    I believe the second implementation (const reference) is correct as:

    1. the returned object is immutable and therefore upholds the rules of encapsulation.
    2. it's slightly more efficient as there is no copying of str.

    However the first approach will work almost as well.

提交回复
热议问题