Bug 1703 – invariant(Class) does not work as expected
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Linux
Creation time
2007-11-30T18:12:00Z
Last change time
2015-06-09T01:14:23Z
Keywords
rejects-valid
Assigned to
bugzilla
Creator
markusle
Comments
Comment #0 by markusle — 2007-11-30T18:12:57Z
Hi,
According to the docs I would have expected the following to
compile using dmd-2.008
class C
{
int x;
}
void main()
{
invariant(C) c;
c = new C; // (1) ok
}
However, dmd tells me that
test.d(9): Error: cannot implicitly convert expression (new C) of type test.C to invariant(C)
Also, am I assuming correctly that the following should also compile?
If not, how else would one initialize the class?
class C
{
this(int x) { x_ = x; }
int x_;
}
void main()
{
invariant(C) c;
c = new C(10); // ok ??
}
Thanks,
Markus
Comment #1 by caron800 — 2007-12-01T00:48:29Z
On 12/1/07, [email protected] <[email protected]> wrote:
> According to the docs I would have expected the following to
> compile using dmd-2.008
>
> class C
> {
> int x;
> }
>
> void main()
> {
> invariant(C) c;
> c = new C; // (1) ok
> }
>
> However, dmd tells me that
>
> test.d(9): Error: cannot implicitly convert expression (new C) of type test.C
> to invariant(C)
I believe the compiler is correct. Mutable data will not implicitly
convert to invariant data. For that you need an explicit cast (new
always creates mutable data).
There is a template called assumeUnique in std.contracts, but I think
it only works for arrays. In any case, all it does is insert a cast,
so you could just do that manually, as in:
c = cast(invariant(C)) new C;
(You could always ask for a language feature inew :) )
Comment #2 by markusle — 2007-12-01T06:34:26Z
Hi Janice,
Thanks much for your comments and casting works fine
indeed. The main reason I brought this up was that the
docs at http://www.digitalmars.com/d/const3.html
explicitly state that what I posted should be possible
(the snippet of code is pretty much verbatim taken from there).
and works fine for structs but not for classes.
Hopefully, I didn't completely misunderstand the docs.
cheers,
Markus