Thread overview | |||||
---|---|---|---|---|---|
|
September 20, 2016 Append const to array | ||||
---|---|---|---|---|
| ||||
struct A { ulong[] x; } struct B { ulong x; } void main() { B[] b; const(B) xx = B(1); b ~= xx; // Works A[] c; const(A) yy = A([1]); c ~= yy; // Does not } What gives? |
September 20, 2016 Re: Append const to array | ||||
---|---|---|---|---|
| ||||
Posted in reply to Yuxuan Shui | On Tuesday, September 20, 2016 22:23:08 Yuxuan Shui via Digitalmars-d-learn wrote:
> struct A {
> ulong[] x;
> }
> struct B {
> ulong x;
> }
> void main() {
> B[] b;
> const(B) xx = B(1);
> b ~= xx; // Works
>
> A[] c;
> const(A) yy = A([1]);
> c ~= yy; // Does not
> }
>
> What gives?
const(A) means that the ulong[] inside is const(ulong[]). When yy is copied
to be appended to c, it goes from const(A) to A, which means that
const(ulong[]) would need to be sliced and and set to ulong[], which would
violate const, because it would mean that the last element in c could mutate
then elements of its x, which would then mutate the elements in yy.
- Jonathan M Davis
|
September 21, 2016 Re: Append const to array | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jonathan M Davis | On Tuesday, 20 September 2016 at 22:38:33 UTC, Jonathan M Davis wrote:
> On Tuesday, September 20, 2016 22:23:08 Yuxuan Shui via Digitalmars-d-learn wrote:
>> struct A {
>> ulong[] x;
>> }
>> struct B {
>> ulong x;
>> }
>> void main() {
>> B[] b;
>> const(B) xx = B(1);
>> b ~= xx; // Works
>>
>> A[] c;
>> const(A) yy = A([1]);
>> c ~= yy; // Does not
>> }
>>
>> What gives?
>
> const(A) means that the ulong[] inside is const(ulong[]). When yy is copied
> to be appended to c, it goes from const(A) to A, which means that
> const(ulong[]) would need to be sliced and and set to ulong[], which would
> violate const, because it would mean that the last element in c could mutate
> then elements of its x, which would then mutate the elements in yy.
>
> - Jonathan M Davis
That makes sense, thanks.
|
Copyright © 1999-2021 by the D Language Foundation