www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Arrays and non-copyable elements

reply Jack Applegame <japplegame gmail.com> writes:
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
}
```
Jun 07 2020
parent reply Steven Schveighoffer <schveiguy gmail.com> writes:
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
Jun 07 2020
parent reply Stanislav Blinov <stanislav.blinov gmail.com> writes:
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.
Jun 07 2020
parent Steven Schveighoffer <schveiguy gmail.com> writes:
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
Jun 07 2020