I do not understand copy constructors

Tejas notrealemail at gmail.com
Thu Aug 12 12:19:56 UTC 2021


On Thursday, 12 August 2021 at 11:54:22 UTC, Learner wrote:
> On Thursday, 12 August 2021 at 10:10:17 UTC, rikki cattermole 
> wrote:
>>
>> On 12/08/2021 9:36 PM, Learner wrote:
>>> It seems that there is no easy way to transition from a 
>>> postblit to a copy constructor, no?
>>
>> struct Foo {
>> 	this(ref Foo other) {
>> 		foreach(i, v; other.tupleof)
>> 			this.tupleof[i] = v;
>> 	}
>>
>> 	@disable this(this);
>> }
>
> This results to:
>
>     Generating an `inout` copy constructor for `struct A` 
> failed, therefore instances of it are uncopyable

Just add ```inout``` inside ```this(ref inout/*notice the inout*/ 
Foo other) inout/*notice the inout*/```

Example code:
```d
struct Foo {
  	this(ref inout Foo other) inout {
  		foreach(i, v; other.tupleof)
  			this.tupleof[i] = v;
  	}

  	@disable this(this);
     int a;
     float b;
     double c;
  }

void main(){
     immutable Foo a;
     const Foo c;
     Foo b = a;//mutable b and immutable a
     const Foo d = c;//const d and const c
     Foo e = c;//mutable e and const c
     immutable Foo f = b;//immutable f and mutable b
     const Foo g = b;//const g and mutable b
}

```


More information about the Digitalmars-d-learn mailing list