I do not understand copy constructors

drug drug2004 at bk.ru
Thu Aug 12 11:19:34 UTC 2021


12.08.2021 14:07, drug пишет:
> 12.08.2021 12:36, Learner пишет:
> 
>>  > It seems that there is no easy way to transition from a postblit to a
>> copy constructor, no?
>>
>>
>>
> 
> You just need both const and mutable copy ctors to replace inout one:
> ```D
> struct A {
>      int[] data;
>      this(ref return scope A rhs) { data = rhs.data.dup; }
>      this(ref return scope const A rhs) const { data = rhs.data.dup; }
> }
> ```
> 
> the mutable copy ctor accepts mutable data and the const copy ctor 
> accepts const and immutable data

but using inout ctor is easier:
```D
struct A {
     int[] data;
     this(ref return scope inout A rhs) /* no inout here */ { data = 
rhs.data.dup; }
}
```
The problem is that if you qualify the ctor itself then if you pass 
const/immutable rhs to it then the ctor is const/immutable too (like the 
args) and of course you cannot modify this, so the error.

To make a copy ctor you need to qualify copy ctor args as inout but the 
copy ctor itself shall be mutable and have no const,immutable or inout 
qualifier.


More information about the Digitalmars-d-learn mailing list