Design with appender: good or bad?
monarch_dodra
monarchdodra at gmail.com
Thu Apr 10 06:47:21 PDT 2014
On Thursday, 10 April 2014 at 13:29:39 UTC, Chris wrote:
> Thanks. But the question was not about how to print it to
> console, but whether there are any hidden dangers in using
> Appender in this way, like the one Rene mentioned.
AFAIK, no. In fact, arguably, it's saf*er*, since an appender has
a "true" reference semantic, whereas a slice has "half reference
semantics": If you modify an *item* all instances will see it,
but if you *add* some items, only 1 will see it.
But I guess it kind of depends on what you want.
EG:
//----
struct S1
{
Appender!(string[]) buf;
string name;
this(string name) {
this.name = name;
buf = appender!(string[]);
}
public void addItem (string item) @property
{
buf.put(item);
}
@property string[] items()
{
return buf.data;
}
}
struct S2
{
string[] items;
string name;
this(string name) {
this.name = name;
}
public void addItem (string item) @property
{
items ~= item;
}
}
void main()
{
foreach ( S ; TypeTuple!(S1, S2) )
{
auto bob = S("Bob");
bob.addItem("PS4");
auto bob2 = bob;
bob2.addItem("XBOXONE");
writefln("%s.bob %s", S.stringof, bob.items);
writefln("%s.bob2 %s", S.stringof, bob2.items);
}
}
//----
S1.bob ["PS4", "XBOXONE"]
S1.bob2 ["PS4", "XBOXONE"]
S2.bob ["PS4"]
S2.bob2 ["PS4", "XBOXONE"]
//----
That said, it feels like you are using Appender like a container.
Maybe "Array" is a better fit?
More information about the Digitalmars-d-learn
mailing list