Property discussion wrap-up

Zach the Mystic reachBUTMINUSTHISzach at gOOGLYmail.com
Wed Jan 30 19:35:31 PST 2013


On Thursday, 31 January 2013 at 01:14:36 UTC, TommiT wrote:
> 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".

Now classes are a different kettle of fish. I haven't thought 
them out and I don't think I need to. They may work seamlessly 
with my idea or be fraught with problems, I don't know.

But there will never be a need for a new empty struct. The 
operator new makes no sense. There's no data! Imagine an empty 
struct as a list of functions under a namespace. That's all it 
really is. Except it just so happens that this namespace has a 
bunch of built-in functions which allow it to appear in normal 
code as if it's a *type*. Want it to appear with parens, so it 
looks like a function you're calling? Just define opCall inside 
the struct. Want it to appear before an equals sign. Just define 
opAssign. As an array? opIndex. A basic type such as an int? 
opGet. There will never be any need to create an instance. You 
only need one. At runtime, there is no evidence of a pointer at 
all, just normal data being passed to normal functions.


More information about the Digitalmars-d mailing list