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

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

问题描述

在 C++11 中,它允许您像这样创建 0 长度的 C 数组和 std:array:

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. 所以我在想一个没有空间存储的数组有什么用?
  2. 其次,什么是零长度数组?如果是指针,它指向哪里?

推荐答案

你的第一个例子不是标准的 C++,而是 一个gccclang 允许的扩展,它是灵活数组 以及这个这个问题的答案:真的需要灵活的数组成员吗?a> 解释了此功能的许多优点.如果您使用 -pedantic 编译 标志,您将在 gcc 中收到以下警告:

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:

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

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

以及clang中的以下警告:

警告:零大小数组是一个扩展 [-Wzero-length-array]

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

对于第二种情况,零长度 std::array 允许使用更简单的通用算法,而不必对 零长度 进行特殊处理,例如模板非size_t 类型的类型参数.正如 cppreference 部分 std::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:

零长度数组(N == 0)有一个特殊情况.在这种情况下,array.begin() == array.end(),这是一些唯一值.对大小为零的数组调用 front() 或 back() 的效果是不确定的.

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::array)有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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