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

前端之家收集整理的这篇文章主要介绍了c – 拥有一个C样式数组的std ::数组是否合法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以使用像std :: array< int [2] [2],2>这样的东西吗?作为int [2] [2] [2]的替代,就像std :: array< int,2>可以用来代替int [2]吗?

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

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

看起来,与C风格的数组不同,std :: array的std :: array不能保证具有完全紧凑的内存,因为std :: array可能包含填充.

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

解决方法

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

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

Given an allocator type A and given a container type X having a value_­type identical to T and an allocator_­type identical to allocator_­traits<A>​::​rebind_­alloc<T> and given an lvalue m of type A,a pointer p of type T*,an expression v of type (possibly const) T,and an rvalue rv of type T,the following terms are defined. If X is not allocator-aware,the terms below are defined as if A were allocator<T> — no allocator object needs to be created and user specializations of allocator<T> are not instantiated:

  • T is Erasable from X means that the following expression is well-formed:
    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.

原文链接:https://www.f2er.com/c/118001.html

猜你在找的C&C++相关文章