Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

e.g.

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.

like image 202
davidcorne Avatar asked Jul 23 '15 10:07

davidcorne


People also ask

Can we use typedef for function pointer?

A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.

What is typedef function in C++?

The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.

What is the scope of a typedef?

A typedef is scoped exactly as the object declaration would have been, so it can be file scoped or local to a block or (in C++) to a namespace or class.


1 Answers

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.

like image 198
Jonathan Wakely Avatar answered Oct 13 '22 16:10

Jonathan Wakely