如何声明一个成员的访问者? [英] How to declare an accessor to a member?

查看:125
本文介绍了如何声明一个成员的访问者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些类中,访问器声明为 getName1 ,在其他类中 getName2 。从使用的角度来看,它看起来是相同的。在一个体面的编译器中,有没有任何性能优势?在任何情况下,我应该只使用两个中的一个?

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;
}


推荐答案

> 更快,因为不需要进行复制(虽然在很多情况下, 返回 - 值优化

但是,它也增加了耦合。考虑如果你想改变类的内部实现会发生什么你以不同的方式存储名称(即不再在字符串中)。将不再有通过引用返回的东西,因此您还需要更改公共接口,这意味着客户端代码将需要重新编译。

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.

这篇关于如何声明一个成员的访问者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆