Casting away const

Steven Schveighoffer schveiguy at yahoo.com
Mon Aug 9 14:06:41 PDT 2010


On Mon, 09 Aug 2010 15:49:12 -0400, Simen kjaeraas  
<simen.kjaras at gmail.com> wrote:

> Simen kjaeraas <simen.kjaras at gmail.com> wrote:
>
>> Steven Schveighoffer <schveiguy at yahoo.com> wrote:
>>
>>> Note also that the optimization you stated is not possible, even  
>>> without casting away const, but would be possible on an immutable  
>>> class.  But the fact that the compiler cannot peek into the  
>>> implementation of the opAssign means it's forced to make no  
>>> assumptions about the result of opAssign
>>
>> You're right, I was thinking of immutable.
>
> This said, one of the reasons casting away const is undefined, is because
> the underlying type may be immutable.

Right.  After reading all these replies, I think the way it looks to me is  
technically it's undefined to cast away const/immutable and write the  
data.  But, in certain circumstances, I think it will be possible to write  
portable code that works on all compilers that does this.

It's like a threading race condition.  If you simply allow unchecked  
access to a variable, it's undefined, you get races and can be using a  
partially written value, but slap a mutex around it, and the variable  
suddenly becomes well defined and behaves perfectly.  The compiler cannot  
guarantee this, nor detect it, but the programmer can determine based on  
analysis of all the code that it's safe.

-Steve


More information about the Digitalmars-d-learn mailing list