Topic: Simple question on std:list
Author: "Richard Browne" <richb@pobox.com.au>
Date: 1999/09/03 Raw View
Say I have a std::list object, with an iterator 'it' that points to some
element. If I add new elements, or delete elements other than the one it
points to, I know that it remains valid. However, I am unsure whether the
element itself is allowed be moved as a result of reallocation.
For example:
#include <list>
#include <assert.h>
void main()
{
std::list<char> my_list;
const std::list<char>::iterator it = my_list.insert(my_list.begin());
const char& first_element = my_list.front();
for (int i = 0; i < 1000; ++i) {
my_list.push_back(0);
}
assert(*it == first_element); // <-- ?
}
Am I guaranteed that the address of what it points to will not change?
All help appreciated.
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]
Author: hinnant@anti-spam_twcny.rr.com (Howard Hinnant)
Date: 1999/09/03 Raw View
In article <936333430.179107@jaguarundi>, "Richard Browne"
<richb@pobox.com.au> wrote:
> Say I have a std::list object, with an iterator 'it' that points to some
> element. If I add new elements, or delete elements other than the one it
> points to, I know that it remains valid. However, I am unsure whether the
> element itself is allowed be moved as a result of reallocation.
>
> For example:
>
> #include <list>
> #include <assert.h>
>
> void main()
> {
> std::list<char> my_list;
>
> const std::list<char>::iterator it = my_list.insert(my_list.begin());
> const char& first_element = my_list.front();
>
> for (int i = 0; i < 1000; ++i) {
> my_list.push_back(0);
> }
>
> assert(*it == first_element); // <-- ?
> }
>
> Am I guaranteed that the address of what it points to will not change?
>
> All help appreciated.
The standard says that list::push_back (and other list modifiers) does not
invalidate iterators **and references**.
With a minor modification (your insert call is missing a value to insert),
the standard does guarantee your program to work.
Disclaimer: (to ward off posts concerning my use of the word guarantee)
The standard demands that the return type of main is int, and does not
guarantee that there is ample resources to store 1000 char's in your list.
-Howard
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]