Return from a vector and dereference it

Hi,

Why doesn't the code below work please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
using namespace std;


auto test() {
	vector<int> vi = { 2, 4, 6 };
	return vi.begin();
}

int main()
{
	auto p = test();
	cout << *p << endl;

	return 0;
}



When we dereference vi.begin();, it gives the value 2, but after sending it to p in main(), dereferencing p doesn't match, while both are pointers to int!
Last edited on
Returning an iterator to a local object is kinda like returning a pointer to a local object.
Once the test function ends, the vector vi no longer exists. Any pointer or iterator to it is invalidated, and shouldn't be used.
thanks, that's right.

How about this one. It should seemingly work properly, but in essence, not!

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
33
34
#include <iostream>
#include <vector>
using namespace std;

class T {

public:
	auto vBegin() { return vi.begin(); }

	auto vEnd() {
		if (vi.size() == 0) fill_in();
		return vi.end();
	}

	void fill_in() {
		vi = { 2,4,6 };
	}

private:
	vector<int> vi;
};

int main()
{
	T t;
	auto p = t.vBegin();

	for (; p != t.vEnd(); ++p)
		cout << *p << ' ';
	cout << endl;

	return 0;
}
Put
t.fill_in();
between lines 25 and 26, not in the call to t.vEnd().

You could change the iterator which would be returned by vi.begin() when you reset your vector. Incrementing p then becomes meaningless.
Last edited on
When you initialize p, vi has no contents, so vi.begin() is the same as vi.end(). You don't add contents to vi until you check vEnd(). When you do add the contents, p is already at the end of the vector.

Have T's constructor call fill_in().
Topic archived. No new replies allowed.