How to break const
Jonathan M Davis
jmdavisProg at gmx.com
Mon Jun 18 01:06:59 PDT 2012
On Monday, June 18, 2012 09:14:59 Mehrdad wrote:
> Okay, how about this? http://ideone.com/VMlzS
>
> Does this break const?
>
>
> import std.stdio;
> class S
> {
> this(int a)
> {
> this.a = a;
> this.increment = { this.a++; };
> }
> int a;
> void delegate() increment;
> void oops() const { this.increment(); }
> }
> void main()
> {
> auto c = new const(S)(0);
> writeln(c.a);
> c.oops();
> writeln(c.a);
> }
I'm not sure. I believe that it gets away with it, because none of the member
variable are actually const until the constructor has completed, in which
case, you've managed to hide away a non-const reference to what is supposed to
be a const object. Technically, I don't think that it breaks const, but it
does seem rather off. However, if the object isn't actually const until the
constructor is complete, then it _is_ perfectly legimate.
Now, what worries me is that this seems to compile:
import std.stdio;
class S
{
this(int a) immutable
{
this.a = a;
this.increment = { this.a++; };
}
int a;
void delegate() increment;
void oops() const { this.increment(); }
}
void main()
{
auto c = new const(S)(0);
writeln(c.a);
c.oops();
writeln(c.a);
}
As I understand it, that should _not_ compile. An immutable constructor should
disallow all mutation of member variables after their initial assignment
within the constructor, but clearly that's not happening. It even allows
adding
++a;
on its own inside of the constructor, so it's not just an issue with the
delegate either.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list