拥有一个C样式数组的std ::数组是否合法?

问题描述 投票:7回答:1

我可以使用像std::array<int[2][2], 2>这样的东西作为int[2][2][2]的替代品,就像std::array<int, 2>可以用来代替int[2]吗?

我真正需要的可能是一个静态大小的多维数组

  1. 具有“适当的”价值语义,并且
  2. 被连续存储在内存中。

似乎与C风格的数组不同,std::arraystd::array不能保证具有完全紧凑的内存,因为std::array可能包含填充。

如果我使用像std::array<int[2][2], 2>这样的东西,我可能会遇到什么问题?也许这是一个太模糊的问题,但很难弄清楚为什么我不舒服,有些怀疑使用它为我的目的。

c++ arrays
1个回答
3
投票

不,它会导致未定义的行为。

容器value_typemust be Erasable from the container type,其中Erasable在[container.requirements.general] paragraph 15中定义:

给定一个分配器类型A并给出一个容器类型X,其value_­typeT相同,allocator_­typeallocator_­traits<A>​::​rebind_­alloc<T>相同,并给出m类型的左值Ap类型的指针T*,类型(可能是vconst的表达式T,和rv类型的右值T,定义了以下术语。如果X不支持分配器,则下面的术语定义为A是allocator<T> - 不需要创建分配器对象,并且不实例化allocator<T>的用户专精:

  • ...
  • TX的可擦除意味着以下表达形式良好:allocator_traits<A>::destroy(m, p)

因为std::array不支持分配器,我们需要检查allocator_traits<allocator<int[2][2]>>::destroy(m, p)是否形成。

由于std::allocator没有成员函数destroy(在C ++ 17中弃用),std::allocator_traits::destroy将直接调用int[2][2]的(伪)析构函数。这is ill-formed因为int[2][2]不是scalar type

© www.soinside.com 2019 - 2024. All rights reserved.