Is the data in nested std::arrays guaranteed to be contiguous?(嵌套的 std::arrays 中的数据是否保证是连续的?)
问题描述
std::array 中的数据是否保证连续?例如:
Is the data in std::array<std::array<T,N>, M> guaranteed to be contiguous? For example:
#include <array>
#include <cassert>
int main()
{
enum {M=4, N=7};
typedef std::array<char,N> Row;
typedef std::array<Row, M> Matrix;
Matrix a;
a[1][0] = 42;
const char* data = a[0].data();
/* 8th element of 1D data array should be the same as
1st element of second row. */
assert(data[7] == 42);
}
断言是否保证成功?或者,换句话说,我可以依靠 Row 的末尾没有填充吗?
Is the assert guaranteed to succeed? Or, to put it another way, can I rely on there being no padding at the end of a Row?
为了清楚起见,对于这个例子,我希望整个矩阵的数据是连续的.
Just to be clear, for this example, I want the data of the entire matrix to be contiguous.
推荐答案
不,在这种情况下不保证连续性.
No, contiguity is not guaranteed in this case.
std::array 保证是一个聚合,并以这样一种方式指定,即用于存储的底层数组必须是该类型的第一个数据成员.
std::array is guaranteed to be an aggregate, and is specified in such a way that the underlying array used for storage must be the first data member of the type.
但是,没有要求sizeof(array,也没有要求最后没有未命名的填充字节对象或 std::array 除了底层数组存储之外没有数据成员.(不过,包含额外数据成员的实现充其量是不寻常的.)
However, there is no requirement that sizeof(array<T, N>) == sizeof(T) * N, nor is there any requirement that there are no unnamed padding bytes at the end of the object or that std::array has no data members other than the underlying array storage. (Though, an implementation that included additional data members would be, at best, unusual.)
这篇关于嵌套的 std::arrays 中的数据是否保证是连续的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:嵌套的 std::arrays 中的数据是否保证是连续的?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
