mardi 5 juillet 2016

C++11 - what does it mean to initialize a variable to a reference


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

Aucun commentaire:

Enregistrer un commentaire