Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of std :: array<T, 0>?

Tags:

c++

c++11

stl

I found that there is a template partial specialisation in std::array for std::array<T, 0>.

template <typename T>
struct array<T, 0> {
    //...
    typedef typename conditional<is_const<_Tp>::value, const char,
                                char>::type _CharType;
    struct  _ArrayInStructT { _Tp __data_[1]; };
    alignas(_ArrayInStructT) _CharType __elems_[sizeof(_ArrayInStructT)];
    //...
}

So what is the purpose of implementing std::array<T, 0>?

Thanks very much!

like image 700
Jonny0201 Avatar asked Feb 12 '20 05:02

Jonny0201


People also ask

What is the purpose of std :: array?

std::array provides fixed array functionality that won't decay when passed into a function. std::array is defined in the <array> header, inside the std namespace. Just like the native implementation of fixed arrays, the length of a std::array must be known at compile time.

Is std :: array zero initialized?

std::array::array For elements of a class type this means that their default constructor is called. For elements of fundamental types, they are left uninitialized (unless the array object has static storage, in which case they are zero-initialized).

What is std :: array in C++?

std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically.

What are the benefits of using the std :: array?

std::array provides many benefits over built-in arrays, such as preventing automatic decay into a pointer, maintaining the array size, providing bounds checking, and allowing the use of C++ container operations.


1 Answers

The reason is, simply, uniformity. When you're writing templates it's much easier to be able to always write std::array<Ty, N> than to have to write a special case when N is 0. That kind of uniformity comes up often: new int[0], operator new(0), std::malloc(0), for (int i = 0; i < N; ++i) when N is 0.

like image 110
Pete Becker Avatar answered Oct 19 '22 12:10

Pete Becker