Destructors, const structs, and opEquals

Franciszek Czekala home at valentimex.com
Sat Dec 4 01:00:05 PST 2010


> Officially, opEquals has to have the signature:
>
> struct Foo {
> bool opEquals(const ref Foo x) const {...}
> }
>
> But this disallows comparisons with rvalues.
> eg,
>
> Foo bar() { Foo x = 1; return x; }
> Foo y=1;
> assert( y == bar() ); // doesn't compile
>
> You can get around this by declaring a non-ref opEquals.
> But this fails if Foo has a destructor.
>
> If a struct has a destructor, it cannot be const(this is bug
3606)
> ---
> struct S {
>     ~this() {}
> }
>
> void main() {
>     const S z;
> }
> ---
> bug.d(6): Error: destructor bug.S.~this () is not callable using
argument types ()
> -------
> Likewise, it can't be a const parameter (this is bug 4338).
> void foo(const S a) {}
> It works to have it as a const ref parameter.
>
> Everything will work if you declare a const ~this(), but that
seems a little nonsensical. And you cannot have both const and non-
const ~this().
>
> I'm a bit uncertain as to how this is all supposed to work.
> (1) Should temporaries be allowed to be passed as 'const ref'?
> (2) If a struct has a destructor, should it be passable as a
const parameter? And if so, should the destructor be called?
>
>
I was wondering. Why cannot things be done simply? In Ada95 one
has:

function "=" (X,Y: in T) return Boolean;

for every type T, simple or composite, records and classed
included. Ada95 has been around for 15 years and did not gain any
popularity even though it was described as better than C++. I wish
D all best, but in view of the problem signaled in this post the
prospects are dim. D seems just a bit too complicated for a
compelling replacement of existing languages.

Anyway, if struct has value semantics then perhaps the argument to
opEquals should have simply 'in' mode? In Ada95 the 'in' mode of
the arguments does not determine how the arguments are passed
internally to the function. The compiler can choose to pass them
by value or by reference as suitable. Since the 'in' mode makes
the arguments constant inside, it does not really matter how the
arguments are passed, so why burden the user with this knowledge?


More information about the Digitalmars-d mailing list