【问题标题】:Is the size of std::array<T, N> guaranteed to be equal to the size of T[N]? [duplicate]std::array<T, N> 的大小是否保证等于 T[N] 的大小? [复制]
【发布时间】:2016-03-27 08:57:24
【问题描述】:

看来这段代码可以工作(所以它编译得很好),我在这里要问的是:是否保证 sizeof(std::array) 与 sizeof(equivalent_Carray) 相同?

struct MyClass {
  std::array<float, 4> arr;  
  float carr[4];

  std::array<float, 4> cfunction() {
    std::array<float, sizeof(carr) / sizeof(float)> out;
    return out;
  }

  std::array<float, 4> function() {
    // Is this guaranteed to be the same as sizeof(carr) / sizeof(float)??
    std::array<float, sizeof(arr) / sizeof(float)> out;
    std::cout << sizeof(arr);
    return out;
  }
};

int main()
{
    MyClass obj;
    obj.function();
}

【问题讨论】:

  • 请做一个有用的问题标题。

标签: c++ arrays c++11 c++14 sizeof


【解决方案1】:

没有。

我们通过std::array&lt;T, N&gt; 获得的唯一保证是:

  • size()N;
  • &amp;a[n] == &amp;a[0] + n 代表所有 0 &lt;= n &lt; N
  • 数组是可以使用语法初始化的聚合 (8.5.1)

    array<T, N> a = { initializer-list };
    

没有什么能阻止实现者添加尾随成员,尽管我不知道为什么会这样做。

【讨论】:

  • 我想知道为什么我不能只使用arr.size() (implicit use of 'this' pointer is only allowed within the evaluation of a call to a 'constexpr' member function) 来初始化我的数组大小。我的意思是..它是一个成员变量,但它也是一个std::array,所以它的大小不能改变
  • @Dean:因为为了与其他容器保持一致,他们将其设为非constexpr,尽管语义不可变。很遗憾,如果你问我。几周前确实有人问过这个问题。 IIRC 有可能在 C++17 中发生这种变化,但不要引用我的话。我们真正需要的是static constexpr size_t size() const { return N; } 成员函数或任何语法。
  • 我同意,这太可怕了。
  • @Dean:嗯,它是 C++。
  • tuple_size 适用于 std::array。 array::size() 是 constexpr,但遗憾的是不是静态的。
猜你喜欢
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 2019-08-16
  • 2021-02-27
  • 2020-05-21
相关资源
最近更新 更多