digitalmars.D.learn - subtlety or bug?
- Carl Sturtivant (56/56) May 10 2017 The following compiles and runs correctly.
- Carl Sturtivant (6/6) May 10 2017 Aha, https://dlang.org/spec/struct.html#struct-destructor says
The following compiles and runs correctly. https://forum.dlang.org/post/tzwsohkcqrkqotbwnhjb forum.dlang.org But if I add a destructor to the reference struct template as follows, it no longer compiles, and the complaints are not about the destructor. ``` ~this() { ptr = null; } ``` refsim.d(39): Error: generated function refsim.reference!int.reference.opAssign (reference!int p) is not callable using argument types (int) refsim.d(42): Error: generated function refsim.reference!int.reference.opAssign (reference!int p) is not callable using argument types (int) These are complaining about lines where reference!int variables are assigned integers. What's going on? Here's the code linked to above without the destructor that works. ``` struct reference(T) { T* ptr; this(ref T x) { ptr = &x; } import std.exception : enforce; ref T cnvrt() property { enforce( ptr !is null); return *ptr; } ref T cnvrt(T x) property { enforce( ptr !is null); return *ptr = x; } alias cnvrt this; } void main() { int i; auto ri = reference!int(i); auto ri2 = reference!int(ri); assert(ri.ptr==ri2.ptr); i = 99; assert(i==ri && i==ri2 && ri==ri2); ri = 100; assert(i==ri && i==ri2 && ri==ri2); ri2 = 101; assert(i==ri && i==ri2 && ri==ri2); } ```
May 10 2017
Aha, https://dlang.org/spec/struct.html#struct-destructor says that An identity assignment overload is required for a struct if one or more of these conditions hold: * it has a destructor so this is the above condition coming into play.
May 10 2017