Opaque structs

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Jun 27 18:40:31 PDT 2013


Traditionally using opaque structs in D when interfacing with C (where
one should only ever use such structs with a pointer) are implemented
like so:

-----
struct S;

void main()
{
    S* s1;  // ok
    S s2;  // linker error
}
-----

Unfortunately this tends to spawn unreadable error messages:

-----
test.d(3): Error: struct test.S unknown size
test.d(3): Error: struct test.S no size yet for forward reference
test.d(3): Error: struct test.S unknown size
test.d(3): Error: struct test.S no size yet for forward reference
test.d(12): Error: variable test.main.s2 no definition of struct S
test.d(3): Error: struct test.S unknown size
test.d(3): Error: struct test.S no size yet for forward reference
-----

I was thinking we could also implement opaque structs like so:

-----
struct S
{
    @disable this();
    @disable this(this);
}

void main()
{
    S* s1;
    S s2;
}
-----

The error is then:

-----
Error: variable test.main.s2 initializer required for type S
-----

The question is, is a disabled ctor and postblit enough?

Note that if we implement Issue 8728[1], we could even create a better
error message via:

-----
struct S
{
    @disable("S is an opaque C type and must only be used as a pointer")
    this();

    @disable("S is an opaque C type and must only be used as a pointer")
    this(this);
}

void main()
{
    S* s1;  // ok
    S s2;  // user error
}
-----

[1] : http://d.puremagic.com/issues/show_bug.cgi?id=8728


More information about the Digitalmars-d-learn mailing list