Is sizeof(T) == sizeof(int)?
arrays, c++, sizeof
Solution
You essentially are asking, given:
struct T {
U handle;
};
whether it's guaranteed that `sizeof(T) == sizeof(U)`. No, it is not.
Section 9.2/17 of the ISO C++03 standard says:
A pointer to a POD-struct object, suitably converted using a `reinterpret_cast`, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.
Suppose you have an array of `struct T`. The vice versa part means that the address of any of the `T::handle` members must also be a valid address of a `struct T`. Now, suppose that these members are of type `char` and that your claim is true. This would mean that `struct T` would be allowed to have an unaligned address, which seems rather unlikely. The standard usually tries to not tie the hands of implementations in such a way. For your claim to be true, the standard would have to require that `struct T` be allowed to have unaligned addresses. And it would have to be allowed for all structures, because `struct T` could be a forward-declared, opaque type.
Furthermore, section 9.2/17 goes on to state:
[Note: There might therefore be unnamed padding within a POD-struct object, but not at its beginning, as necessary to achieve appropriate alignment.]
Which, taken a different way, means that there is no guarantee that there will never be padding.
Problem
I've been poring over the draft standard and can't seem to find what I'm looking for. If I have a standard-layout type ``` struct T { unsigned handle; }; ``` Then I know that `reinterpret_cast<unsigned*>(&t) == &t.handle` for some `T t;` The goal is to create some `vector<T> v` and pass `&v[0]` to a C function that expects a pointer to an array of unsigned integers. So, does the standard define `sizeof(T) == sizeof(unsigned)` and does that imply that an array of `T` would have the same layout as an array of `unsigned`? While this question addresses a very similar topic, I'm asking about the specific case where both the data member and the class are standard layout, and the data member is a fundamental type. I've read some paragraphs that seem to hint that maybe it might be true, but nothing that hits the nail on the head. For example: § 9.2.17 Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types This isn't quite what I'm looking for, I don't think.