获取 std::array 底层数组的内存大小的最简单方法?

Simplest way to get memory size of std::array's underlying array?

这是获取 std::array::data() returns 内容的内存大小的 simplest/shortest 方法吗?

arr.size() * sizeof(arr.value_type)

编辑:我的问题不准确。 "size in memory" 我的意思是数组中包含的所有元素(它们本身)的大小,所以如果例如它们是指向结构的指针,我只想要指针的大小,而不是指向的结构。我也不想包括 std::arr 实现的任何可能开销的大小。只是数组元素。

有人建议 sizeof(arr)。这点:What is the sizeof std::array<char, N>?不敢苟同。虽然它似乎可以在我的机器上工作,但我想知道标准保证什么。

您可以直接在 std::array 实例上使用 sizeof 运算符:

sizeof(arr)

示例:

struct foo
{
    int a;
    char b;
};

int main()
{
    std::array<foo, 10> a;
    static_assert(sizeof(foo) == 8);
    static_assert(sizeof(a) == 80);
}

live example on wandbox


来自cppreference

std::array is a container that encapsulates fixed size arrays.

This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member.

不保证sizeof(std::array<T,N>) == N*sizeof(T),但保证sizeof(std::array<T,N>) >= N*sizeof(T)。额外的大小可能是命名(但未指定)成员 and/or 未命名填充。

保证来自包装的 T[N] 数组必须是 std::array<T,N> 的第一个成员,但未指定其他成员。

阅读documentation of std::array。所以是的,它可能是。或者试试

  (arr.size()-1) * sizeof(arr.value_type) + sizeof(std::array<T,1>)

但我只会使用 sizeof(arr)

顺便说一句,我不确定你对此有任何正式的保证。我猜想标准理论上允许 std::arraystd::vector 相同,除了 resize() 和其他一些方法将被隐藏。但是没有一个理智的实现会这样做(因为 std::array 被发明来将普通数组打包在一个类似于向量的容器中)。

也许只允许 std::array-s 至多两个元素(但否则会抛出一些异常)的实现可能符合标准。

我了解到你问的是:array<value_type,N> arr,即arr.begin()arr.end()之间的元素集合占用的内存大小是多少?

答案是sizeof(value_type)*N,这个在标准中是有说明的,但是需要经过一些处理才能得出这个结论。

在 C++ 标准中 [dcl.array](这是关于 (c-)array 而不是 std::array):

An object of array type contains a contiguously allocated non-empty set of N subobjects of type T.

in [expr.add](这里术语数组指的是 (c-)array):

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the expression P points to element x[i] of an array object x with n elements, 86 the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element x[i + j] if 0 ≤ i + j ≤ n; otherwise, the behavior is undefined. Likewise, the expression P - J points to the (possibly-hypothetical) element x[i − j] if 0 ≤ i − j ≤ n; otherwise, the behavior is undefined.

并且在[array.data]中(这里术语数组指的是std::array):

constexpr T* data() noexcept;
constexpr const T* data() const noexcept;

Returns: A pointer such that data() == addressof(front()), and [data(), data() + size()) is a valid range.

所以 data() return 到 std::array 元素的有效范围,这个范围可以使用指向 value_type 的指针进行迭代,所以它遵循指针算法它遵循 (c-) 数组索引的规则,并且 (c-) 数组的元素是连续的。 Q.E.D.

因为没有人发布任何比我的第一个猜测更好的东西,而且 sizeof(arr) 很可能 不保证不包括 任何可能的额外 std::array's 字段我选择这个作为接受的答案。

arr.size() * sizeof(arr.value_type)

如果有人提出更好的建议,我很乐意接受他们的回答。

我认为你必须求助于使用像

这样的辅助函数
template <typename T>
auto getSize(T& t) -> size_t {
    typename T::size_type size = t.size();
    size_t value_type_size = sizeof(typename T::value_type);

    return size * value_type_size;
}