On Saturday, 20 May 2017 at 10:48:54 UTC, Gary Willoughby wrote:
In the following code, the `_foo` pointer (of the Foo struct) is null in the first call to the destructor. Why is this? I think it's got something to do with the foreach loop but I'm not sure. Any ideas?

Oof. Dangerous stuff. As Moritz pointed out, default opAssign will call the destructor on Foo. I should, however, elaborate further. You're dealing with uninitialized data. calloc() gives you zero-initialized block, which is not necessarily how Foo.init would look (it does in this case, but that's not true in general case). malloc() gives you a potentially garbage-filled block, which is even more dangerous.

When filling an array of uninitialized values, use std.algorithm.moveEmplace(src, dst) instead of assignment. And, if you have destructors, you have to call the destructors manually when you free the array. Furthermore, since Bar._data is an array of Foos, and Foo has a pointer in it, you might want to register the Bar._data array with the GC (GC.addRange, GC.removeRange). Unless you're willing to manually make sure that GC *never* sees those pointers.

Reply via email to