[英]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 算法一起使用,只需使用
begin
和end
函数:
// 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>
storesN
elements of typeT
, so thatsize() == N
is an invariant.array<T, N>
的实例存储了N
个T
类型的元素,因此size() == N
是一个不变量。 The elements of anarray
are stored contiguously , meaning that ifa
is anarray<T, N>
then it obeys the identity&a[n] == &a[0] + n
for all0 <= 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 variableelems
is shown for exposition only, to emphasize thatarray
is a class aggregate.[注意:成员变量
elems
仅用于说明,以强调array
是 class 聚合。 The nameelems
is not part ofarray
'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.