Bug 23444 – Can't append non-copyable struct value to an array
Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P3
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2022-10-29T15:13:24Z
Last change time
2024-03-08T14:58:33Z
Assigned to
No Owner
Creator
Paul Backus
Comments
Comment #0 by snarwin+bugzilla — 2022-10-29T15:13:24Z
As of DMD 2.100.2, the following program fails to compile:
---
struct NoCopy
{
@disable this(this);
}
void main()
{
NoCopy[] a;
a ~= NoCopy(); // error
}
---
The error message is:
---
bug.d(9): Error: struct `bug.NoCopy` is not copyable because it has a disabled postblit
---
However, this error is spurious. The program below compiles without errors and produces no output when run, because the postblit is not actually called at runtime:
---
struct NoCopy
{
this(this)
{
import std.stdio;
writeln("copied");
}
}
void main()
{
NoCopy[] a;
a ~= NoCopy(); // ok; no output
}
---
Comment #1 by razvan.nitu1305 — 2023-04-04T12:24:50Z
This seems to be done on purpose, see this comment: https://issues.dlang.org/show_bug.cgi?id=7579#c5 .
In short, if you concatenate a struct instance with a disabled postblit you subject yourself to the possibility of the runtime doing copies behind your back (for example, when reallocations happen). This seems pretty nasty because the alternative would be to accept this code and then either do copies that do not call the postblit behind the scenes or have some druntime internal failures (provided that the hooks are properly templated).