Bug 15924 – formattedWrite doesn't write to empty appender
Status
RESOLVED
Resolution
WORKSFORME
Severity
normal
Priority
P3
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2016-04-14T08:40:11Z
Last change time
2019-12-07T10:54:46Z
Assigned to
No Owner
Creator
keepitsimplesirius
Comments
Comment #0 by keepitsimplesirius — 2016-04-14T08:40:11Z
Following code raises assertion failure (buffer.data() returns empty string). With the marked line it passes. It seems like formattedWrite is unable to write to empty appender.
import std.array;
import std.format;
int main() {
Appender!string buffer;
// buffer.put(""); // with this line it passes
formattedWrite(buffer, "foo");
assert("foo" == buffer.data());
return 0;
}
Comment #1 by ag0aep6g — 2016-04-15T17:02:17Z
The issue is, of course, that a default initialized Appender does not have an associated array yet. When such a not-really-initialized Appender is copied, the copy and the original are completely independent from each other. Writing to one doesn't affect the other. In the formattedWrite call, buffer is being copied, so formattedWrite writes to a location of which buffer doesn't know.
Other variants that work:
----
auto buffer = appender!string;
formattedWrite(buffer, "foo");
Appender!string buffer;
formattedWrite(&buffer, "foo");
----
As for a fix, I'm not sure what should be done here. `disable this();` for Appender is an idea, but that would probably break quite some code.
Comment #2 by keepitsimplesirius — 2016-04-15T19:43:58Z
Thanks for explanation. What about making formattedWrite to take argument by reference instead of value?
Comment #3 by ag0aep6g — 2016-04-15T22:19:31Z
(In reply to keepitsimplesirius from comment #2)
> Thanks for explanation. What about making formattedWrite to take argument by
> reference instead of value?
That would make your code work, but it would break other reasonable code that's probably already out there. Like this:
----
string buffer;
formattedWrite(appender(&buffer), "foo");
----
`auto ref` may be an option.