有什么用0长度数组(或std ::数组)的? [英] What is the use of 0-length array (or std::array)?

查看:138
本文介绍了有什么用0长度数组(或std ::数组)的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11它允许你创建一个 0 长度C数组和 STD:阵列这样的

  INT ARR1 [0];
的std ::阵列ARR2< INT,0取代;


  1. 所以我想那是什么没有一个空间来存储使用数组?

  2. 其次什么是零长度数组?如果它是一个指针,在那里它指向?


解决方案

您第一个例子是不是标准的C ++,但的扩展的两个 GCC 允许,它的版本灵活的阵列回答问题:是灵活的阵列成员真的有必要解释此功能的诸多优点?如果您使用 -pedantic 标志,你会收到以下警告在 GCC


  

警告:ISO C ++禁止零大小的数组ARR1[-Wpedantic]


铛以下警告


  

警告:零大小的数组是一个扩展[-Wzero长度阵列]


至于你的第二个案例零长度的std ::阵列允许简单的泛型算法,无需特殊情况下的零长度的,例如类型的模板非类型参数的为size_t 的。至于性病::阵列的 CP preference节指出这是一个特殊情况:


  

有为零长度数组(N == 0)的特殊情况。在这种情况下,array.begin()== array.end(),它是一些独特的价值。调用一个零大小的阵列上前方()或背面()的效果是不明确的。


这也使其与其他序列容器一致从而可以也是

In C++11 it allows you to create a 0 length C array and std:array like this:

int arr1[0];
std::array arr2<int,0>;

  1. So I'm thinking what is the use of a array that doesn't have a space to store?
  2. Secondly what is the zero length array? If it is a pointer, where does it pointing to?

解决方案

Your first example is not standard C++ but is an extension that both gcc and clang allow, it is version of flexible arrays and this answer to the question: Are flexible array members really necessary? explains the many advantages of this feature. If you compiled using the -pedantic flag you would have received the following warning in gcc:

warning: ISO C++ forbids zero-size array 'arr1' [-Wpedantic]

and the following warning in clang:

warning: zero size arrays are an extension [-Wzero-length-array]

As for your second case zero-length std::array allows for simpler generic algorithms without having to special case for zero-length, for example a template non-type parameter of type size_t. As the cppreference section for std::array notes this is a special case:

There is a special case for a zero-length array (N == 0). In that case, array.begin() == array.end(), which is some unique value. The effect of calling front() or back() on a zero-sized array is undefined.

It would also make it consistent with other sequence containers which can also be empty.

这篇关于有什么用0长度数组(或std ::数组)的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆