Thread overview | ||||||
---|---|---|---|---|---|---|
|
June 07, 2020 Arrays and non-copyable elements | ||||
---|---|---|---|---|
| ||||
I think it should compile. ``` struct NonCopyable { int a; this(this) @disable; } void main() { NonCopyable[] arr = [NonCopyable(1), NonCopyable(2)]; // ok arr ~= NonCopyable(3); // fails } ``` |
June 07, 2020 Re: Arrays and non-copyable elements | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jack Applegame | On 6/7/20 7:25 PM, Jack Applegame wrote:
> I think it should compile.
>
> ```
> struct NonCopyable {
> int a;
> this(this) @disable;
> }
>
> void main() {
> NonCopyable[] arr = [NonCopyable(1), NonCopyable(2)]; // ok
> arr ~= NonCopyable(3); // fails
> }
> ```
This is a bug, please file. What is likely happening is that the template is not moving the data to the underlying C call.
-Steve
|
June 08, 2020 Re: Arrays and non-copyable elements | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | On Monday, 8 June 2020 at 00:31:10 UTC, Steven Schveighoffer wrote:
> This is a bug, please file. What is likely happening is that the template is not moving the data to the underlying C call.
>
> -Steve
That is not a bug, it's a shortcoming of garbage-collected arrays. D arrays are not equipped to deal with non-copyable values. The ~= has to expect to copy contents of arr, since at runtime there may be multiple references to it, i.e:
auto storage = [NonCopyable(a), /* .... */];
auto arr = storage[1 .. 3];
arr ~= NonCopyable(n);
This would need to allocate a new array and copy contents of storage[1 .. 3] into it.
|
June 07, 2020 Re: Arrays and non-copyable elements | ||||
---|---|---|---|---|
| ||||
Posted in reply to Stanislav Blinov | On 6/7/20 10:07 PM, Stanislav Blinov wrote:
> On Monday, 8 June 2020 at 00:31:10 UTC, Steven Schveighoffer wrote:
>
>> This is a bug, please file. What is likely happening is that the template is not moving the data to the underlying C call.
>>
>
> That is not a bug, it's a shortcoming of garbage-collected arrays. D arrays are not equipped to deal with non-copyable values. The ~= has to expect to copy contents of arr, since at runtime there may be multiple references to it, i.e:
Ah yes, I was not considering the possibility of having to copy the existing data, I was only looking at the new value.
So this is not a bug.
It's not going to be easy to use D arrays for dynamic allocation of data. What you probably have to do is pre-allocate a large array and then assign new values to the elements.
Possibly an array type that destroys the original data via memory setting the data to the init value when reallocating would be the only way to fix this.
-Steve
|
Copyright © 1999-2021 by the D Language Foundation