What guarantees does D 'const' provide, compared to C++?

Mehrdad wfunction at hotmail.com
Thu Aug 16 17:36:53 PDT 2012


On Friday, 17 August 2012 at 00:13:58 UTC, bearophile wrote:
> Mehrdad:
>
>>> On the note of casting away const, I don't believe that is 
>>> the operation which is undefined, however modifying const is 
>>> undefined as it could be pointing to immutable data.
>>
>> Oh, then that's not what I'd understood. Seems just like C++ 
>> then.
>
> Are you sure?


Yes, I'm pretty sure that something like

	const int x = 5;
	int* p = const_cast<int*>(&x);
	*p = 6;

is undefined behavior, because x is a const object.

However,

	int y = 5;
	const int& x = y;
	int* p = const_cast<int*>(&x);
	*p = 6;

is well-defined, because the object is mutable.



At least, that's my understanding of C++; feel free to correct me 
if I'm wrong.


More information about the Digitalmars-d mailing list