C++ 14 intro.cpp States:
a most derived object shall have a non-zero size and shall occupy one or more bytes of storage
Why did they have to state
non-zero size
and
one or more bytes of storage
When can it have one but not the other ?
The two parts are actually saying different things.
a most derived object shall have a non-zero size
That means sizeof
using an object will return a non-zero size.
a most derived object ... shall occupy one or more bytes of storage
That means the object occupies some bytes (one or more) of memory.
If the second statement didn't exist then that could mean that sizeof
would report a non-zero size but the object might not actually use any memory.
Without the first statement it could mean that sizeof
could return zero but the object would still take up space in memory.
Both are needed and orthogonal to each other.
There are cases in which a class may have a non-zero size (returned by sizeof
) but it does not actually occupy any space on memory. For example, Empty Base Optimization (EBO) is used to make a base part of a derived object occupies no space on memory as shown in example below:
#include <stdio.h>
struct Base {};
struct Derived : Base
{
int a;
};
int main()
{
printf("sizeof(Base) = %d\n", sizeof(Base));
Derived* p = new Derived;
void* p1 = p;
void* p2 = &p->a;
if(p1 == p2) { printf("Good compiler\n"); }
return 0;
}
Compiled with gcc 4.8.4 on Ubuntu 14.04 x64.
Output:
sizeof(Base) = 1
Good compiler
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With