Bug 6288 – std.conv.to removes const/immutable when converting a class
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2011-07-11T10:19:00Z
Last change time
2011-10-09T03:47:02Z
Keywords
patch
Assigned to
nobody
Creator
schveiguy
Comments
Comment #0 by schveiguy — 2011-07-11T10:19:14Z
The code in std.conv.to looks like this for converting to base/derived class:
/**
Object-to-object conversions throw exception when the source is
non-null and the target is null.
*/
T toImpl(T, S)(S value) if (is(S : Object) && is(T : Object))
{
auto result = cast(T) value;
if (!result && value)
{
throw new ConvException("Cannot convert object of static type "
~S.classinfo.name~" and dynamic type "~value.classinfo.name
~" to type "~T.classinfo.name);
}
return result;
}
This does not take into account that cast can easily remove const or immutable decorations.
For example:
import std.conv;
class C {}
class D : C {}
void main()
{
const(C) c = new D;
D d = to!D(c);
assert(d !is null);
}
This compiles as of 2.054, and clearly is removing const without requiring a cast.
Unfortunately, cast() is the mechanism to do dynamic conversions, so the logic to allow compilation needs to check that const is not being removed or immutable is not being removed/added.