Re: Sizeof struct containing T?
On 9/12/07 9:59 AM, in article
1189594703.753237.282960@k79g2000hse.googlegroups.com, "Daniel Kr?gler"
<daniel.kruegler@googlemail.com> wrote:
On 11 Sep., 12:22, Jiang <goo.mai...@yahoo.com> wrote:
On Sep 11, 12:32 am, Martin Bonner <martinfro...@yahoo.co.uk> wrote:
sizeof(U) >= sizeof(T), but it reallistically is possible for
sizeof(U) > sizeof(T).
If T can be any type then it is possible that sizeof(U)
will be even smaller than sizeof(T).
No, that is impossible, v.i.
The example posted conclusively shows otherwise: that sizeof(U) can indeed
be less than sizeof(T), even when U is a class type that declares a member
of type T.
struct t
{
char a[32];
};
typedef t& T;
OK, T is a reference type, but this is *not* the same as T.
On the contrary, "t&" is the same as T. Removing the typedef makes this
point even more clear:
template <class T>
struct U
{
T b;
};
assert( sizeof( U< t& > ) < sizeof( t& ));
struct U
{
T b; // ignore its initialization ...
};
U contains now a *reference* to a t. Note also, that it is
impossible to omit the initialisation of a variable of reference type.
But U declares a member of type T - not a member of type T& - but of T
itself.
Furthermore, it is possible to omit the initialization of the U::b member.
Because sizeof() does not evaluate its operand, no U object is allocated, so
b does not have to be initialized in order for the sizeof(U) operation to
succeed.
There exists a special rule in C++ for sizeof in namely [expr.sizeof]/2 :
"When applied to a reference or a reference type, the result is the size
of the referenced type[..]"
which effectively guarantees:
static_assert(sizeof(X) == sizeof(X&), "sizeof is immune to
references");
But there is no guarantee in C++ that sizeof() when applied to a struct, U,
containing member of a reference type, T - has to have the same size or
greater than sizeof(T). So according to the sizeof() operator in C++, the
size of a class object may be less than the size of one of its members.
Q.E.D.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]