返回对私有成员的引用

时间:2018-01-16 00:43:40

标签: c++ reference

我有一个班级

class SomeClass {
  public:
    using DType = std::vector<int>;

    DType& data1() {   // this should return a reference to data
      return data;
    }

    DType data2() {   // this should return a copy to data
      return data;
    }

  private:
    DType data;
}

我的理解是,如果我这样做

SomeClass temp;
auto d1 = temp.data1();  // this should NOT do any copying just create a new ref
auto d2 = temp.data2();  // this supposed to copy the data?

我正在读一本书,当我这么做时它会说

auto d1 = temp.data1()

它将复制整个数据并分配给d1 ......这本书是否有任何错误?

* * * ************从阅读其他人的答案更新*****************

似乎“汽车”在这里做了一些有趣的事情。我想如果我这样做:

std::vector<int>& d1 = temp.data1() . // this is not copying

但如果我这样做:

std::vector<int> d1 = temp.data1() . // this is copying

1 个答案:

答案 0 :(得分:5)

您的理解不正确。 auto d1 = temp.data1();将制作副本。如果您想要参考,请使用auto& d1 = temp.data1();