What is the best way to return string in C++?

后端 未结 7 1079
刺人心
刺人心 2020-12-04 15:16

My question is simple: if I have some class Man and I want to define member function that returns man\'s name, which of the following two variants shall I prefer?

Fi

7条回答
  •  眼角桃花
    2020-12-04 15:53

    Since you want to create a getter for a field of your class, maybe you should go like that: inline const std::string& name() const { return this->name; }

    Since the name is returned as a const reference, it won't be modified outside the class, also no copy will be created by returning the name.

    After that, if you want to manipulate the name you will have to do a copy.

提交回复
热议问题