Bug 7069 – Variant Doesn't Handle Const or Immutable Contents
Status
RESOLVED
Resolution
FIXED
Severity
major
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2011-12-05T21:52:00Z
Last change time
2014-02-15T14:21:53Z
Assigned to
nobody
Creator
debio264
Comments
Comment #0 by debio264 — 2011-12-05T21:52:07Z
Example code:
--------
import std.variant;
class Bob {}
void main() {
immutable(Bob) bob = new immutable(Bob)();
Variant v = bob;
immutable(Bob) bob2 = v.get!(immutable(Bob))();
}
--------
Runtime Error:
core.exception.AssertError@C:\D\dmd2\windows\bin\..\..\src\phobos\std\variant.d(286): immutable(Bob)
This comes from here in std.variant:
--------
static if (is(typeof(*cast(T*) target = *src)))
{
auto zat = cast(T*) target;
if (src)
{
assert(target, "target must be non-null");
*zat = *src;
}
}
else
{
// type is not assignable
if (src) assert(false, A.stringof); // <-- line 286
}
--------
In this case, T is of type immutable(Bob). The check for assignability fails for any immutable type (or any type that contains immutable values) even though technically this code is initializing an immutable value and should be legal.
One way to make this work is to rewrite the above code to this:
--------
static if (is(typeof(*cast(T*) target = *src)))
{
auto zat = cast(T*) target;
if (src)
{
assert(target, "target must be non-null");
*zat = *src;
}
}
else static if (is(T V == const(U), U) || is(T V == immutable(U), U))
{
auto zat = cast(U*) target;
if (src)
{
assert(target, "target must be non-null");
*zat = *(cast(U*) (src));
}
}
else
{
// type is not assignable
if (src) assert(false, A.stringof);
}
--------
Which is basically casting away immutability to copy the reference.
This sort of situation makes a compelling argument for the idea of a tail const reference, or a mutable reference to const or immutable data.
Comment #1 by sandford — 2011-12-06T16:32:22Z
I've added this to my test suite for improving variant. It causes compile-time errors in my current code base, but I will work on a fix.
Comment #2 by public — 2013-11-12T04:59:01Z
This bug prevents std.concurrency from working as advertised (can't send immutable messages) : http://forum.dlang.org/post/[email protected]
Raising importance to "major" because of that.
Comment #3 by opantm2+dbugs — 2014-02-15T14:21:53Z
This appears to have been fixed in git master: https://github.com/D-Programming-Language/phobos/commit/6e7eabbd42a7f2e3e555081e1b17893c3c18b6f8
import std.variant, std.stdio;
class Bob {}
void main() {
immutable(Bob) bob = new immutable(Bob)();
writeln(cast(void*)bob);
Variant v = bob;
immutable(Bob) bob2 = v.get!(immutable(Bob))();
writeln(cast(void*)bob2);
}
Prints out
1091E4FF0
1091E4FF0