Behaviour of std::list:begin() when list is empty
14288 просмотра
2 ответа
Does the following give defined results in terms of the C++ standard?
std::list<int> myList;
std::list<int>::iterator myIter = myList.begin(); // any issues?
myList.push_back( 123 );
myIter++; // will myIter point to the 123 I pushed?
I can test this out on the compiler I'm using... but I'd like a more definitive answer.
Автор: omatai Источник Размещён: 12.11.2019 09:27Ответы (2)
19 плюса
All standard iterator and container types behave the same in this regard:
§23.2.1 [container.requirements.general] p6
begin()
returns an iterator referring to the first element in the container.end()
returns an iterator which is the past-the-end value for the container. If the container is empty, thenbegin() == end()
;
And table 107 in §24.2.3 [input.iterators]
demands that as a precondition for ++it
, it
shall be dereferenceable, which is not the case for past-the-end iterators (i.e., what you get from end()
), as such you're treading into the dreaded domain of undefined behaviour.
4 плюса
std::list<int> myList;
std::list<int> myIter = myList.begin();
The iterator has the same value as if you were initializing it with myList.end()
. The iterator is initialized to on-past-the-end position. Even after you push an element into the list the iterator still points one-past-the-end. If you increment it, you are invoking undefined behaviour.
UPDATE:
E.g., if you compile your snippet with GCC with -D_GLIBCXX_DEBUG, the resulting executable will abort:
/usr/include/c++/4.6/debug/safe_iterator.h:236:error: attempt to increment
a past-the-end iterator.
Objects involved in the operation:
iterator "this" @ 0x0x7fffc9548fb0 {
type = N11__gnu_debug14_Safe_iteratorINSt9__cxx199814_List_iteratorIiEENSt7__debug4listIiSaIiEEEEE (mutable iterator);
state = past-the-end;
references sequence with type `NSt7__debug4listIiSaIiEEE' @ 0x0x7fffc9548fb0
}
zsh: abort (core dumped) ./listiter
Автор: wilx
Размещён: 29.05.2012 05:20
Вопросы из категории :
- c++ What are the barriers to understanding pointers and what can be done to overcome them?
- c++ Какой самый простой способ для анализа файла INI в C ++?
- c++ Когда вы должны использовать «друг» в C ++?
- c++ Как вы очищаете переменную stringstream?
- c++ В C ++ конструктор и деструктор могут быть встроенными функциями?
- c++ Что такое виртуальный базовый класс в C ++?
- c++ В чем разница между #include <filename> и #include "filename"?
- c++ Какой самый лучший бесплатный детектор утечки памяти для программы на C / C ++ и ее подключаемых библиотек DLL?
- c++ Как преобразовать std :: string в LPCWSTR в C ++ (Unicode)
- c++ Regular cast vs. static_cast vs. dynamic_cast
- std Как узнать, присутствует ли элемент в std :: vector?
- std контейнер для быстрого поиска имени
- std Можете ли вы удалить элементы из списка std :: list, просматривая его?
- std Есть ли эквивалент strtol, который не требует строки с нулевым символом в конце?
- std Почему "использование пространства имен std;" считается плохой практикой?
- std Как найти / найти и заменить в стандартной строке?
- std В чем разница между использованием структуры с двумя полями и парой?
- std Как объединить значения хеш-функции в C ++ 0x?
- std Заменить часть строки другой строкой
- std C читать файл по строкам