Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can an object have either but not both of non zero size , one or more bytes of storage?

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 ?

like image 711
New Student Avatar asked Jul 16 '17 06:07

New Student


2 Answers

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.

like image 92
Some programmer dude Avatar answered Sep 20 '22 12:09

Some programmer dude


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
like image 22
duong_dajgja Avatar answered Sep 22 '22 12:09

duong_dajgja