Casting away const
Steven Schveighoffer
schveiguy at yahoo.com
Mon Aug 9 07:13:31 PDT 2010
On Mon, 09 Aug 2010 09:57:47 -0400, bearophile <bearophileHUGS at lycos.com>
wrote:
> Steven Schveighoffer:
>> I thought it was "you're on your own", not undefined behavior. The
>> former
>> implies there is some "right" way to do this if you know more about the
>> data than the compiler, the latter implies that there is no right way to
>> cast away const. Am I wrong?
>
> In my opinion if this thing is well designed then you go in undefined
> behaviour only when you change the contents of something after you have
> removed its const nature with a cast. Just casting const away and then
> reading the data can't be undefined behaviour, otherwise casting const
> away is useless and can be totally disallowed.
Casting away const just to read the data is useless. You can read const
data without a cast.
But my understanding is that casting away const to write should be doable
if you know what you're doing. If this is undefined behavior, then that's
fine, I'm just unclear on what "undefined behavior" actually means. I
thought "undefined behavior" means that you cannot count on the behavior
to work in the future.
An example of where casting away const to write should be allowed is for a
hypothetical mutable member:
class C
{
private Mutable!(int) cache = -1;
int expensiveFunction() const { return cache == -1 ? cache =
_expensiveFunctionImpl() : cache; }
private int _expensiveFunctionImpl() const {...}
}
If this is undefined, then something like this cannot be relied on, even
when performance is critical.
-Steve
More information about the Digitalmars-d-learn
mailing list