C ++ 11 - 将变量初始化为引用意味着什么

时间:2016-06-21 00:49:34

标签: c++ c++11

#include<vector>
using namespace std;

class Foo
{
  private:
    vector<int> m_vec;
  public:
    vector<int> getFoo()
    {
      return m_vec; // returns a copy of m_vec
    }
    vector<int>& getFooRef()
    {
      return m_vec; // returns a reference of m_vec
    }
};

int main()
{
  Foo foo;
  vector<int> x = foo.getFoo(); // init x with a copy of m_vec
  vector<int>& y = foo.getFooRef(); // y is a reference to foo.m_vec - no new copy is created
  vector<int> z = foo.getFooRef(); // what happens here?? Is the copy constructor invoked?
  vector<int>& a = foo.getFoo(); // what happens here?? Is `a` a reference to a copy of m_vec?
  return 0;
}

1 个答案:

答案 0 :(得分:3)

当你这样做时

vector<int> z = foo.getFooRef();

编译器使用=运算符右侧的引用来执行z运算符左侧的变量=的初始化。

初始化的实际操作的性质由左侧确定,即z。由于z 不是引用,因此运算符=会将通过引用获得的向量内容复制到z