Property discussion wrap-up

TommiT tommitissari at hotmail.com
Wed Jan 30 17:14:31 PST 2013


On Thursday, 31 January 2013 at 00:15:36 UTC, Zach the Mystic 
wrote:
>> The problem of using empty struct variables is that they take 
>> up memory. They have to, because you can make a pointer to a 
>> variable and then you can dereference that variable. There has 
>> to be at least a byte of memory to dereference.
>>
>> So, really, the only zero-overhead way to do this is to 
>> introduce a new keyword that creates something that you can't 
>> take the address of, because it kind of doesn't exist (like a 
>> namespace). It exists only in the sense that it can be used to 
>> tell the compiler which operators and functions to call. 
>> That's what my namespace_thingy is.
>
> I disagree. The compiler can easily tell if a struct is defined 
> with no data, and simply optimize away the pointer in the 
> process.

Here's Bjarne Stroustrup's reasoning for this design choice
http://www.stroustrup.com/bs_faq2.html#sizeof-empty

Q: Why is the size of an empty class not zero?

A: To ensure that the addresses of two different objects will be 
different. For the same reason, "new" always returns pointers to 
distinct objects. Consider:

class Empty { };

void f()
{
     Empty a, b;
     if (&a == &b) cout << "impossible: report error
                            to compiler supplier";

     Empty* p1 = new Empty;
     Empty* p2 = new Empty;
     if (p1 == p2) cout << "impossible: report error
                            to compiler supplier";
}

There is an interesting rule that says that an empty base class 
need not be represented by a separate byte:

struct X : Empty {
     int a;
     // ...
};

void f(X* p)
{
     void* p1 = p;
     void* p2 = &p->a;
     if (p1 == p2) cout << "nice: good optimizer";
}

This optimization is safe and can be most useful. It allows a 
programmer to use empty classes to represent very simple concepts 
without overhead. Some current compilers provide this "empty base 
class optimization".


More information about the Digitalmars-d mailing list