简体   繁体   中英

std::vector< T >::iterator with accessible constructor

g++ implementation of STL allows me in my client code to construct an iterator of std::vector<T>::iterator type with arbitrary address value:

int* i_ptr;
std::vector< int >::iterator it(i_ptr);

Is it standard ability, or just rudiment of implementation?

Where it designed to be used?

This is just an implementation detail, it is not even guaranteed to compile by the standard. It is also not listed in gcc's implementation defined behavior nor in the GNU C++ extensions, so your snippet may break at any version change.

Don't rely on this "working" in any sense in your code.

In Visual Studio 2017 RC this does not compile:

main.cpp(8): error C2664: 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>::
_Vector_iterator(std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>> &&)':
cannot convert argument 1 from 'int *' to
'const std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>> &'

I do not think that it is a standard ability. Just an implementation defined feature.

In many implementations vector iterators are just simple pointers. So if you have a vector< T > then iterator is simply a pointer to type T . It is done for some optimization purposes.

In such implementations it is possible to create iterators initialized from the pointers to type T because you can initialize a pointer to type T by another pointer of such type.

But it is implementation defined, of course, if an iterator defined as a pointer to type T or not.

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