3

It seems this code works (so it compiles fine), what I'm asking here is: is it guaranteed that sizeof(std::array) is the same as 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();
}
Dean
  • 6,610
  • 6
  • 40
  • 90

1 Answers1

5

No.

The only guarantees we get with std::array<T, N> are that:

  • size() is N;
  • &a[n] == &a[0] + n for all 0 <= n < N;
  • An array is an aggregate (8.5.1) that can be initialized with the syntax

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

There is nothing stopping the implementor from adding a trailing member, though I know of no reason why one would.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I wonder why I can't just use `arr.size()` (`implicit use of 'this' pointer is only allowed within the evaluation of a call to a 'constexpr' member function`) to initialize my array size. I mean.. it is a member variable but it is also a `std::array` so its size can't change – Dean Dec 21 '15 at 10:10
  • 4
    @Dean: Because they made it non-`constexpr` for consistency with other containers, despite the immutable semantics. A shame, if you ask me. Someone actually did ask about this a few weeks ago. IIRC there was a possibility of this changing in C++17, but don't quote me on it. What we really need is a `static constexpr size_t size() const { return N; }` member function or whatever the syntax is. – Lightness Races in Orbit Dec 21 '15 at 10:13
  • I agree, this is horrible. – Dean Dec 21 '15 at 10:21
  • 1
    @Dean: Well, it's C++. – Lightness Races in Orbit Dec 21 '15 at 10:25
  • `tuple_size` works on std::array. `array::size()` is constexpr, but sadly not static. – Marc Glisse Dec 21 '15 at 10:46