Returning ref to a vector vs returning vector

WHy if I return vector(the commented function getVector) the first two elements are not initialized,if I return ref to vector everithing is OK
Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

#include <iostream>
#include <vector>
using namespace std;

class A
{
public:
    A()
    {
        int input;
        cout<<"Enter value: ";
        while(cin>>input)
            vec.push_back(input);
    }

   //vector<int> getVector(){return vec;}
   const vector<int>& getVector(){return vec;}
private:
    vector <int>vec ;
};
ostream& operator<<(ostream&out,A obj)
{
    for(vector<int>::const_iterator beg=begin(obj.getVector());beg!=end(obj.getVector());beg++)
      out<<*beg<<",";
      return out;
}
int main()
{
   A o1;
   cout<<o1;
}
This is a subtle one...
If you were to return a copy and not a reference like this
vector<int> getVector(){return vec;}

This this line
for(vector<int>::const_iterator beg=begin(obj.getVector());beg!=end(obj.getVector());beg++ is a BIG problem because:

beg=begin(obj.getVector()) will be pointing to one vector copy
but will be testing for the end of the vector against end(obj.getVector()) which is another seperate vector copy.

These are TWO DIFFERENT vectors - (or more to the point - TWO different copies of obj.vec).

[[I would have thought though that the program would print out for a very long time and possible crash as the end iterator would never match with beg unless by pure luck]]

That is why returning the reference works - because then the two interators beg and end will be testing against the SAME vector variable.


Topic archived. No new replies allowed.