How to declare an accessor to a member?

孤者浪人 提交于 2019-12-25 08:18:16

问题


In some of the classes accessors are declared like getName1 and in others like getName2. From the usage perspective, it looks identical. Are there any performance benefit of one over the other in a decent compiler? Are there any cases where I should use only one of the two?

class MyClass
{
  public:
    MyClass(const string& name_):_name(name_)
  {
  }
    string getName1() const
    {
      return _name;
    }
    const string& getName2() const
    {
      return _name;
    }
  private:
    string _name;
};

int main()
{
  MyClass c("Bala");
  string s1 = c.getName1();
  const string& s2 = c.getName1();
  string s3 = c.getName2();
  const string& s4 = c.getName2();
  return 0;
}

回答1:


Returning by reference is potentially faster, because no copy needs to be made (although in many circumstances the return-value optimization applies.

However, it also increases coupling. Consider what happens if you want to change the internal implementation of your class so that you store the name in a different way (i.e. no longer in a string). There will no longer be something to return by reference, so you will also need to change your public interface, which means client code will need to be recompiled.




回答2:


string getName1() const
{
    return _name;
}

The compiler can seriously do RVO(return value optimization) in this case.

This article from Dave Abrahams may help.



来源:https://stackoverflow.com/questions/9616689/how-to-declare-an-accessor-to-a-member

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!