If I have a class that has a vector as a private member, a get function to access the vector, and I iterator over the vector, the iteration only works correctly if I make a new copy of the vector:

class MyClass {
public:
  typedef vector<int> Vector;
  MyClass();
  ~MyClass() {;}
  Vector getVector() { return m_vector; }; 
private:
  Vector m_vector;
};

MyClass::MyClass() {
  m_vector.push_back(1);
  m_vector.push_back(2);
  m_vector.push_back(3);
  m_vector.push_back(4);
}

int main() {
  MyClass t;

  // This works...
  MyClass::Vector myVector = t.getVector();  
  for(MyClass::Vector::iterator itr = myVector.begin(); itr != myVector.end(); ++itr) {
    cout << (*itr) << " ";
  }
  cout << endl;

  // This doesn't
  for(MyClass::Vector::iterator itr = t.getVector().begin(); itr != t.getVector().end(); ++itr) {
    cout << (*itr) << " ";
  }
  cout << endl;
}

The output from this looks like:

1 2 3 4
0 0 3 4

The second method will even cause a seg fault if the vector template parameter is larger, such as a string, so I assume this is a memory problem. I was just curious if anyone knows why this is. Any help is appreciated.

Cheers,
-El Wape

use references

class MyClass {
public:
  typedef vector<int> Vector;
  MyClass();
  ~MyClass() {;}
  Vector&  getVector() { return m_vector; }; 
private:
  Vector m_vector;
};

MyClass::MyClass() {
  m_vector.push_back(1);
  m_vector.push_back(2);
  m_vector.push_back(3);
  m_vector.push_back(4);
}

int main() {
  MyClass t;

  // This works...
  MyClass::Vector& myVector = t.getVector();  
  for(MyClass::Vector::iterator itr = myVector.begin(); itr != myVector.end(); ++itr) {
    cout << (*itr) << " ";
  }
  cout << endl;

  // This doesn't
  for(MyClass::Vector::iterator itr = t.getVector().begin(); itr != t.getVector().end(); ++itr) {
    cout << (*itr) << " ";
  }
  cout << endl;
}
This question has already been answered. Start a new discussion instead.