简体   繁体   中英

Why is the pointer typedef not used in std::vector::data()?

In the API of std::vector there are some typedefs and many functions which return these typedefs.

eg

reference operator[](size_type n);

Where reference and size_type are typedefs.

There is a typedef of pointer which it gets from it's allocator template argument. Why is the function signature of data() like this:

T* data() noexcept;

Rather than:

pointer data() noexcept;

Is there some reasoning behind this? Also why is it T* rather than value_type* .

If you want to check it is section 23.3.6.4 of the standard I have.

The reason data() exists is to get a pointer to the underlying array inside the vector, so that (for example) you can pass it to APIs that work with pointers not iterators.

The pointer typedef is not necessarily a real pointer type, it is a typedef for std::allocator_traits<allocator_type>::pointer which could be some class type that behaves like a pointer (sometimes called a "fancy pointer").

For the default case, std::vector<T> is std::vector<T, std::allocator<T>> , and std::allocator_traits<std::allocator<T>>::pointer is the same type as T* , so it makes no difference.

But for std::vector<T, CustomAllocator<T>> if data() returned a pointer you would not be able to pass it to a function expecting a T* unless is_same<pointer, T*>::value is true.

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