How to break const
Artur Skawina
art.08.09 at gmail.com
Mon Jun 18 15:16:24 PDT 2012
On 06/18/12 23:08, deadalnix wrote:
> Le 18/06/2012 09:14, Mehrdad a écrit :
>> 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);
>> }
>
> Depending on how it is specified, I think you should either :
> - get an error when constructing c, because S isn't « constable ». (delegate type cannot be consted, but can be unconsted safely).
> - get an error when you try to call increment in oops, because the delegate type can't ensure the constness of the operation.
>
I'm afraid that:
- Banning implicit mutable->const conversions would do far more harm,
so this would not be a good solution to the problem.
- Requiring that the type of the delegate "ensure the constness" would
be far too restrictive. (the question would be: "Is any data reachable
via 'this' also reachable through the delegates context pointer?" and
every such delegate would of course need to be "pure" [1].
[This isn't *just* about the above example, you get the same problems
when a const object isn't created but received from somewhere.]
artur
[1] which is a misnomer.
More information about the Digitalmars-d
mailing list