Inability to dup/~ for const arrays of class objects

Peter Williams pwil3058 at bigpond.net.au
Tue May 28 16:32:30 PDT 2013


On 28/05/13 23:41, Steven Schveighoffer wrote:
> On Sat, 25 May 2013 23:58:39 -0400, Peter Williams
> <pwil3058 at bigpond.net.au> wrote:
>
>> Is the inability to use dup and ~ with const arrays of class objects a
>> deliberate design restriction?  I couldn't find mention of it in the
>> specification or Andrei's book and only discovered it the hard way.
>
> It has to be.  There is no cdup.
>
> For any const(T)[] x, the type of x.dup is T[].

Yes, that's why I was doing the dup.  I wanted a non const copy of the 
array.

>  Because this would mean
> that you would remove const, you cannot do that.

I find that dup works for const T[] when T is not a class (although I 
haven't tried it with pointers).  This means I write two versions of my 
code - one for classes (which does (cast(T[])).dup) and one for the rest.

>  Nor can you idup,
> since implicit conversion to immutable is not possible.
>
> As far as I know, ~ works with const arrays of class objects.  Can you
> give a case where it fails?

Looking at my code that caused me to ask this question, I've realised 
that I'm appending a const object onto a no const array.  Once again 
this works for non class objects but not for classes.

I can see why this might be the case as non class objects are probably 
copied by value where the class objects are pointers and the constness 
applies to the items in an array as well the array itself.

If this behaviour is a deliberate design decision I'll accept that and 
(probably) modify my code to use (cast(T[])).dup in all cases.  (At the 
moment, I'm using a single mixin template to handle this issue and the 
inability to use ==, !=, < and friends with constant class objects. 
When that problem goes away I'll do the above modifications.)

This is the type of issue that can come as a surprise when you have a 
working/tested code that suddenly stops compiling when you use it with 
classes.  So a heads up in the documentation would be useful.

Thanks for your response,
Peter


More information about the Digitalmars-d mailing list