How to break const
Christophe Travert
travert at phare.normalesup.org
Wed Jun 20 00:31:03 PDT 2012
Artur Skawina , dans le message (digitalmars.D:170191), a écrit :
>> The proper way to do this is not cast, it is to give the proper
>> constness for all types and methods :
>>
>> struct S {
>> int i; this(int i) { this.i = i; }
>> T* p;
>> void f(int i) const { this.i = i; /*p.i++;*/ }
>> // the commented part is illegal because S.f is const
I missed that. Then I disagree with your use of delegates. The solution
here is to make the free f function to take a non const T*, since the
function tries to modify variables from that T instance (via a
delegate).
I don't mind if the delegate modify an S or a T instance: it should not
modify anything. You use a delegate to store an S structure that you can
modifiy in a const T. This is only one step to consider the following
acceptable:
struct T {
ref int delegate() _i;
this(int i_) { _i = () => i_ }
@property ref int i() const { return _i(); }
}
void foo(const T*)
{
T.i = 10;
}
Would you say that this is not a problem, since you do not modify a T
instance with that delegate?
I prefer to legalise:
struct T
{
mutable int i; // makes modifying i legal, but prevent instanciating
// an immutable T and several optimizations
}
> Only a const T.f would be pointless.
I would allows you to safely call that delegate from a const T instance.
> Like I've already said twice in this thread - it *can* be done (the
> function has to be "pure" too for it to work), but certain delegate
> uses, which are OK now, would be forbidden.
>
> I'm all for fixing this hole - it's just that the proposed "fix" would
> have consequences, which can't simply be ignored.
>
> Language design is not a game of whack-a-mole, where you ban random
> features left and right, because you think you've noticed a problem,
> without properly identifying it nor spending even a single second
> figuring out the implications.
I completely agree with that. And I'm fine with the current situation:
you trust the programmer not to use delegates to break the const system
until we have a proper system to deal with this (inference of constness
of delegates, for a start). But encouraging the use of delegates to
modify variables from a const instance seems wrong to me.
--
Christophe
More information about the Digitalmars-d
mailing list