cplusplus / CWG

Core Working Group
23 stars 7 forks source link

[dcl.type.cv] Normative wording doesn't make program UB if we attempt to write to a const object without modifying it #500

Closed ranaanoop closed 4 months ago

ranaanoop commented 4 months ago

Full name of submitter: Anoop Rana

Reference (section label): [dcl.type.cv], [intro.abstract]

Issue description:

Consider the code:

const int i = 1;
*const_cast<int*>(&i) = 1; //currently only a note in [expr.const.cast#6] makes this UB. So the note should be made normative

Currently it is not clear normatively(since there is a note available but a note is non-normative) if const int i = 1;*const_cast<int*>(&i) = 1; in the above program is UB. In particular, dcl.type.cv says:

Any attempt to modify ([expr.ass], [expr.post.incr], [expr.pre.incr]) a const object ([basic.type.qualifier]) during its lifetime ([basic.life]) results in undefined behavior.

Note the emphasis on the word "modify". But in the example above, we aren't actually "modifying" the old value. Instead we're assigning a value which is the same a the old one. So it is not clear if [dcl.type.cv#4] quoted above is applicable here. The problem mainly is due to the lack of formal definition for the term "modify"

Similarly, there is [intro.abstract#4] that says:

Certain other operations are described in this document as undefined (for example, the effect of attempting to modify a const object).

Here again the word modify is used.

There is however a note available in expr.const.cast#6 that makes the program UB.

[Note 2: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier59 can produce undefined behavior ([dcl.type.cv]). — end note]

So the above note is applicable for the program but the problem is that it is not normative. I suggest to make it normative by removing the Note from [expr.const.cast#6].

ranaanoop commented 4 months ago

Basically, apart from making the note[expr.const.cast#6] normative, we may need to clarify if

modify == write    OR
modify == change
jensmaurer commented 4 months ago

[expr.ass] p2 clearly says that assignment "modifies", independent of the values involved.

ranaanoop commented 4 months ago

@jensmaurer I see, so there doesn't seem to be an immediate need to define "modify".