简体   繁体   中英

Non-const reference type with STL-conforming const Iterator?

I'm working on writing a class that essentially provides a flexible interface to some other data. I would like to iterate over elements using an STL conforming iterator and I'm on the right track by using boost::iterator_facade but I have a question regarding conformance that I can't seem to find an official answer to.

Do I have to provide a const iterator for STL conformance?

I'm using std::shared_ptr<T>& for the non-const dereferenced type that the iterator provides. If I do provide a const iterator, is it acceptable to provide a std::shared_ptr<T>& for my dereferenced type as opposed to a std::shared_ptr<const T>& ?

I have a feeling that the answer to both is no, but I'm unable to find official sources that validate/invalidate those suspicions. I think the second question is more of a matter of semantics.

It is your decision how far the const should reach.

The standard way is, just slap a const on the element returned (possibly by reference) from the const_iterator . That's what the standard library does as well.
So, if the return type for your standard iterator is std::shared_ptr<T>& , then the return type for your constant iterator should be const std::shared_ptr<T>& .

BTW: Did you read the section of the standard describing requirements for iterators, like:

Random Access -> Bidirectional -> Forward -> Input
                                             Output

The full container interface provides const iterators as well as non-const iterators.
If you restrict yourself to those algorithms which won't try to get const iterators, you'll be fine omitting them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM