casting away const and then mutating

anonymous via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 23 11:43:02 PDT 2015


On a GitHub pull request, Steven Schveighoffer (schveiguy), 
Jonathan M Davis (jmdavis), and I (aG0aep6G) have been discussing 
if or when it's ok to cast away const and then mutate the data:

https://github.com/D-Programming-Language/phobos/pull/3501#issuecomment-124169544

I've been under the impression that it's never allowed, i.e. it's 
always undefined behaviour. I think Jonathan is of the same 
opinion.

Steven disagrees and thinks that there are cases where it's ok. 
Namely, this simple case would be ok:

----
int x;
const int *y = &x;
*(cast(int *)y) = 5;
----

As I understand him, he's arguing that since the data is mutable, 
and since no function boundaries are crossed, compilers should 
not be allowed to do anything but the obvious with that code.

I think we've exchanged all arguments we have, yet no one has 
been convinced by the other side.

We've found the language spec to be a bit sparse on this. All I 
could find is essentially "you can't mutate through a const 
reference" [1], but no mention of if/when it's ok to cast a const 
reference to a mutable one (and then mutate).

So the questions are:
Is this specified somewhere?
If it isn't specified, how should it be specified?

[1] http://dlang.org/const3.html


More information about the Digitalmars-d mailing list