A Riddle: what is wrong with this code using std.array.Appender?
Meta
jared771 at gmail.com
Mon Mar 25 18:21:12 UTC 2019
On Monday, 25 March 2019 at 17:32:13 UTC, Steven Schveighoffer
wrote:
>> I can't see the bug in this minimal example:
>>
>> import std.array: Appender;
>>
>> class Class
>> {
>> Appender!(int[]) app = null;
>> }
>>
>> void main()
>> {
>> auto c = new Class();
>> import std.stdio;
>> writeln(c.app.data); //Prints "[]"
>> c.app ~= 10;
>> writeln(c.app.data); //Prints "[10]"
>> }
>>
>> What's the problem?
>
> I have a feeling it's an aliasing thing -- like every app
> member in every class points at the same IMPL struct.
>
> -Steve
Ouch, you're right.
import std.array: Appender;
class Class
{
Appender!(int[]) app = null;
}
void testAppender(Class c)
{
import std.stdio;
writeln(c.app.data);
c.app ~= 10;
writeln(c.app.data);
}
void main()
{
auto c1 = new Class();
auto c2 = new Class();
testAppender(c1); //Prints [] and [10]
testAppender(c2); //Prints [10] and [10, 10]
}
I find that a bit strange, since you'd think that Appender would
initialize its payload on the first append; and it seems like it
does if you look at the code (in Appender.ensureAddable). I'm not
sure how it shakes out that the two Appenders end up sharing the
same memory.
More information about the Digitalmars-d
mailing list