Shared, ref, arrays, and reserve template instantiation

Neia Neutuladh neia at ikeran.org
Thu Sep 13 00:20:14 UTC 2018


On Wednesday, 12 September 2018 at 23:41:16 UTC, James Blachly 
wrote:
> When I add the "shared" attribute to an array, I am no longer 
> able to call reserve because the template won't instantiate:
>
> Error: template object.reserve cannot deduce function from 
> argument types !()(shared(int[]), int), candidates are:
> /dlang/dmd/linux/bin64/../../src/druntime/import/object.d(4091):
>       object.reserve(T)(ref T[] arr, size_t newcapacity)
>
> 1. Shared modifies the type, so the template does not match. 
> Even casting does not seem to work however. Is there something 
> about shared that makes it unable to be taken by reference?
> 2. Is there a workaround for me to be able to preallocate the 
> array?
>
> Kind regards

I'm guessing you tried something like:

     shared char[] x;
     // Doesn't work; it casts the result of x.reserve
     cast(char[])x.reserve(100);
     // Doesn't work; (cast(char[])x) is not an lvalue, so it 
can't be ref
     (cast(char[])x).reserve(100);

Arrays are passed and stored like pointers, and `reserve` 
modifies the array, which is why the thing needs to be ref.

Anyway, it works like this:

     // Cast and store in a variable so it can be ref
     auto b = cast(char[]) x;
     // Okay, reallocates b (changes b.ptr), doesn't change x
     b.reserve(100);
     // Copy changes back to the shared variable
     x = cast(shared) b;



More information about the Digitalmars-d-learn mailing list