Assigning a static array
Ali Çehreli
acehreli at yahoo.com
Thu Apr 18 15:13:14 PDT 2013
On 04/18/2013 02:54 PM, Steven Schveighoffer wrote:
>> The program prints the following because the temporary arrays that are
>> generated when calling the constructors are long gone:
>>
>> [1, 1, 1]
>> [1, 1, 1]
>>
>> The programmer *may have* ;) expected the following output:
>>
>> [1, 1, 1]
>> [2, 2, 2]
>
> There is no guarantee that the incoming array from a variadic function
> is heap-based.
>
> But an interesting way to deal with it is that you can overload with an
> explicit slice parameter, and the variadic version will ONLY bind to a
> variadic call.
Interesting.
Personally, I would not even bother with the second one and expect the
caller to simply put square brackets around the arguments:
import std.stdio;
struct S
{
int[] a;
this(int[] args) // <-- now requires a slice
{
a = args;
}
void foo()
{
writeln(a);
}
}
void main()
{
S[] a;
foreach (i; 0 .. 2) {
a ~= S([i, i, i]); // <-- minor inconvenience
}
foreach (e; a) {
e.foo();
}
}
It is now safe, right?
> And the correct expectation for your code should be:
>
> [0, 0, 0]
> [1, 1, 1]
>
> :)
>
> -Steve
Wow! I made an off-by-6 error there. :)
Ali
More information about the Digitalmars-d-learn
mailing list