clear vector elements

Hello everyone!

I am having some troubles with a vector. If I clear it, I can still access the elements. I made a minimal example:

1
2
3
4
5
6
7
8
9
10
vector<int> numbers;
numbers.push_back(1);

cout << "numbers.size() = " << numbers.size() << endl;
cout << "numbers[0] = " << numbers[0] << endl;

numbers.clear();

cout << "numbers.size() = " << numbers.size() << endl;
cout << "numbers[0] = " << numbers[0] << endl;


Produces the following output

1
2
3
4
numbers.size() = 1
numbers[0] = 1
numbers.size() = 0
numbers[0] = 1


How can I REALLY delete the vector elements, so that after vector.REALLYclear(), I can not access the elements anymore!?
Last edited on
You are accessing something you shouldn't. Try the at() operator, which is limit-checked.

The reason the value remains is because of the vector implementation and it should not be counted on.
Yes I already used the at() operator several times.

But this problem using the [] operator occured to me, and I think it's very painful that this is not catched.

This problem occurs in a larger program, where I loop over several entries of a larger dataset, filling this vector for each entry. Before I fill the vector, I always reset it with vector.clear()

So I have to change all my calls of [] to .at() or is there a way to actually clear the vector elements properly?
There shouldn't be any problem if you just make sure to pass correct arguments to operator[].
The accessor operator of STL containers ARE bounds-checked, but by means of an assert(), which is ignored in release mode.

...which is why you should test all code in debug mode first anyway...
Before I fill the vector, I always reset it with vector.clear()

If your intent is to deallocate the dynamic array held by the vector, clear() does not do that; it only calls the destructors of the elements in the array. Vector's destructor will deallocate it: if your vector is no longer needed, at some point, it should go out of scope and get destructed.

If for some reason, your design prevents vector from being scoped, or you maintain references to it and cannot let it be destructed and constructed, then call the vector member function shrink_to_fit() http://en.cppreference.com/w/cpp/container/vector/shrink_to_fit after calling clear() or, if your compiler is too old to support this, use the swap-with-temporary idiom: http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Clear-and-minimize
What you should be doing is getting the result of vector::size() and being mindful of the valid range. Alternatively, you could use the iterators in the range [vector::begin(), vector::end()).

Topic archived. No new replies allowed.