Cannot compare object.opEquals is not nogc
Lodovico Giaretta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jul 24 08:09:53 PDT 2016
On Sunday, 24 July 2016 at 14:54:11 UTC, Jonathan Marler wrote:
> I believe Rufus was only referring to the virtual methods
> defined in the object class. That would be:
>
> toHash (Note: this is already nothrow, that's intersting and
> quite restrictive)
> opCmp
> opEquals
>
> I think all 3 of these are good candidates for @nogc. However,
> AFAIK, making them @nogc would break any code that implements
> them because they would have to add the @nogc attribute to
> their implementations (unless I am mistaken? Do subclass
> overrides need to explicitly have @nogc if the parent class
> does?). If adding @nogc is not required in the implementation,
> then the only code that would break would be implementations
> that actually do allocate GC memory.
>
> Some would think that restricting GC usage inside these virtual
> methods is a good thing because it has the benefit of
> discouraging memory allocation for these types of operations.
> Really, you probably shouldn't be allocating memory to perform
> a comparison. If you really need to, you can either allocate
> non GC memory, or use a different mechanism then the
> opCmp/opEquals methods.
Yes, making them @nogc would require all existing overrides to be
changed (overrides cannot throw away attributes, but must specify
them explicitly as in the parent class, or stricter).
The real problem making these @nogc is that with the current
state of things @nogc implies nothrow, thus preventing exceptions
(of course we should work to change this thing, and I'm
personally researching convenient ways of doing it; I'll soon
write a post on General about this).
Remember that comparison of complex objects may require
normalization, which may change the objects themselves and
allocate memory. Also, comparisons may throw exceptions that need
the GC (see above). So I'm personally against making those
methods @nogc.
But I'm also against a singly-rooted hierarchy. Removing Object
and having multiple class hierarchies would entirely solve the
issue. But please note that you can already "do" that: if you
never use Object, but always subclasses, the fact that Object
isn't @nogc is no longer an issue. While Object (if it exists)
must support any kind of descendant (and thus cannot pose
arbitrary limitations like @nogc is), the roots of
domain-specific hierarchies can exploit the fact that they are
domain-specific to impose meaningful limitations, based on the
expected usage and behaviour, and can thus be @nogc. And you can
either limit your algorithm inputs to objects of a specific
hierarchy or, if you want it generic, use a template (read as:
you don't use Object explicitly, as if it doesn't exists).
More information about the Digitalmars-d-learn
mailing list