简体   繁体   English

std::array 中的 memory 是否连续?

[英]Is the memory in std::array contiguous?

Is the memory in std::array contiguous? std::array中的 memory 是否连续? Is the following valid/good practice?以下是有效/良好的做法吗?

std::array<type1,Num> arr = //initialize value
type1 * ptr = &arr[0];

Could I then pass ptr to functions expecting a c-style array?然后我可以将ptr传递给期望 c 样式数组的函数吗?

Yes, it is contiguous, as it is basically (and actually) a type arr[10];是的,它是连续的,因为它基本上(实际上)是type arr[10]; , but with STL like interface. ,但与 STL 类似接口。 It also doesn't decay to a pointer on the slightest provocation.它也不会因最轻微的挑衅而衰减为指针。

You can safely pass &arr[0] to a function expecting a C-style array, that's the design goal of it.您可以安全地将&arr[0]传递给 function 期望 C 样式数组,这就是它的设计目标。 To use it with the STL algorithms however, just use the begin and end functions:但是,要将其与 STL 算法一起使用,只需使用beginend函数:

// either members
std::sort(arr.begin(), arr.end());
// or free from <iterator>
std::sort(std::begin(arr), std::end(arr));

For the language lawyer part, §23.3.2.1 [array.overview] p1 :对于语言律师部分, §23.3.2.1 [array.overview] p1

The header <array> defines a class template for storing fixed-size sequences of objects. header <array>定义了一个 class 模板,用于存储固定大小的对象序列。 An array supports random access iterators.数组支持随机访问迭代器。 An instance of array<T, N> stores N elements of type T , so that size() == N is an invariant. array<T, N>的实例存储了NT类型的元素,因此size() == N是一个不变量。 The elements of an array are stored contiguously , meaning that if a is an array<T, N> then it obeys the identity &a[n] == &a[0] + n for all 0 <= n < N . array的元素是连续存储的,这意味着如果a是一个array<T, N>那么对于所有0 <= n < N ,它都遵循恒等式&a[n] == &a[0] + n

And §23.3.2.1 [array.overview] p2 :§23.3.2.1 [array.overview] p2

An array is an aggregate (8.5.1) that can be initialized with the syntax数组是可以使用语法初始化的聚合(8.5.1)

  • array<T, N> a = { initializer-list }; array<T, N> a = {初始化列表};

Also, in p3 , listing the members of std::array :此外,在p3中,列出std::array的成员:

T elems[N]; // exposition only
[ Note: The member variable elems is shown for exposition only, to emphasize that array is a class aggregate. [注意:成员变量elems仅用于说明,以强调array是 class 聚合。 The name elems is not part of array 's interface.名称elems不是array接口的一部分。 —end note ] ——尾注]

Yes the memory of std::array is contiguous.是的, std::array的 memory 是连续的。 On VC10, it is declared as:在 VC10 上,它被声明为:

template<class _Ty,
    size_t _Size>
    class array
    { // fixed size array of values
                ... 
         _Ty _Elems[_Size == 0 ? 1 : _Size];
    };

Where _Elemes is nothing but a simple array of given type.其中_Elemes只不过是给定类型的简单数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM