http://d.puremagic.com/issues/show_bug.cgi?id=7069
Summary: Variant Doesn't Handle Const or Immutable Contents
Product: D
Version: D2
Platform: All
OS/Version: All
Status: NEW
Severity: normal
Priority: P2
Component: Phobos
AssignedTo: [email protected]
ReportedBy: [email protected]
--- Comment #0 from Andrew Wiley <[email protected]> 2011-12-05 21:52:07 PST
---
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.
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------