简体   繁体   中英

why does the value_type function return a pointer in SGI STL

I have got a problem when learning about the iterator traits of SGI STL.

This is a function that get the type of the iterator.

template <class Iterator>
inline typename iterator_traits<Iterator>::value_type* value_type(const Iterator&){
    return static_cast<typename iterator_traits<Iterator>::value_type*>(0);
}

And this is a function who calls the value_type

template <class ForwardIterator, class T>
inline void uninitialized_fill(ForwardIterator first, ForwardIterator last, const T& x){
        __uninitialized_fill(first,last,x,value_type(first));
}

template <class ForwardIterator, class T, class T1>
inline void __uninitialized_fill(ForwardIterator first, ForwardIterator last, const T& x, T1*){
        typedef typename __type_traits<T1>::is_POD_type is_POD;
        __uninitialized_fill_aux(first, last, x, is_POD());
}

I wonder why the value_type function has to return value_type* instead of value_type , I cannot figure out why. In my opinion, it seems that both solutions will be OK.

Hope that someone can help me, Thank you!

I wonder why the value_type function has to return value_type* instead of value_type , I cannot figure out why. In my opinion, it seems that both solutions will be OK.

Note that uninitialized_fill takes that parameter unnamed. We just need its type, and don't want to incur any overhead here.

For an arbitrary type, T , we don't know how to construct it, or if it's copyable or movable. So passing a value_type directly could be impossible and could incur an entirely unwanted copy with side-effects that could be unelidable. But we do know for sure that we can construct a T* from 0 . So using a zero-initialized pointer to value_type is a handy hack in this situation.


Note that SGI's implementation is really old and predates C++98 even, so I would recommend taking a look at a more modern implementation of the standard library.

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