开发者

C++ iterators, default initialization and what to use as an uninitialized sentinel

开发者 https://www.devze.com 2023-02-16 17:32 出处:网络
The Context I have a custom template container class put together from a map and vector. The map resolves a string to an ordinal, and the vector resolves an ordinal (only an initial string to ordinal

The Context

I have a custom template container class put together from a map and vector. The map resolves a string to an ordinal, and the vector resolves an ordinal (only an initial string to ordinal lookup is done, future references are to the vector) to the entry. The entries are modified intrusively to c开发者_如何学Pythonontain a a bool "assigned" and an iterator_type which is a const_iterator to the container class's map.

My container class will use RCF's serialization code (which models boost::serialization) to serialize my container classes to nodes in a network. Serializing iterator's is not possible, or a can of worms, and I can easily regenerate them onces the vectors and maps are serialized on the remote site.

The Question

I need to default initialize, and be able to test that the iterator has not been assigned to (if it is assigned it is valid, if not it is invalid). Since map iterators are not invalidated upon operations performed on it (unless of course items are removed :D) am I to assume that map<x,y>::end() is a valid sentinel (regardless of the state of the map -- i.e., it could be empty) to initialize to ?

I will always have access to the parent map, I'm just unsure wheather end() is the same as the map contents change.

I don't want to use another level of indirection (--i.e., boost::optional) to achieve my goal, I'd rather forego compiler checks to correct logic, but it would be nice if I didn't need to.

Misc

This question exists, but most of its content seems non-sense. Assigning a NULL to an iterator is invalid according to g++ and clang++.

This is another similar question, but it focuses on the common use-cases of iterators, which generally tends to be using the iterator to iterate, ofcourse in this use-case the state of the container isn't meant to change whilst iteration is going on.


You basically got the idea right. A map iterator is only invalidated if the element it points to is removed. map.end() doesn't point to an element, and therefore is never invalidated.

It is NOT the default value of a map iterator, though. Each map object has its own end(), and they are not comparable. This shouldn't be a problem for you; just be careful.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号