I should have expected it, but if you define the "lying" function where the compiler can see the full definition (and don't specify -fno-inline), the loads are optimized out. It made me wonder though whether some variation of this bug might apply : http://www.playingwithpointers.com/ipo-and-derefinement.html
Did you check out the link? https://godbolt.org/g/aaC4B7
My surprise is that none of clang, gcc, or icc give any warning on this with -Wall -Wextra:
1 void copy_const(const int * const arg) {
2 int *copy = (int *)arg;
3 (*copy)++;
4 }
I agree that the cast on line 2 is legal and requires no warning. My surprise is that there is no warning for the write on line 3, since I think this is undefined behavior according the quoted part of the spec. Isn't this trying "to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type"?I realize that the compiler has no obligation to issue a warning here, and in fact is fully entitled to my first-born as soon as it encounters undefined behavior. Still, it seems like it would be a useful place to offer the user a warning just as it does in the case of direct modification:
1 void write_const(const int * const arg) {
2 (*arg)++;
3 }
clang: "error: read-only variable is not assignable"gcc: "error: increment of read-only location '*arg'"
icc: "error #137: expression must be a modifiable lvalue"
That said, it looks like -Wcast-qual is also supported by clang and icc. Clang includes it in "-Weverything", which gcc and icc do not support. Even if not ideal for this issue, I'm sure there are cases where it would help to catch bugs.
This is a distinct object from whatever pointer the caller is passing in. But none of this matters to the special const rule -- that rule is not talking about the pointer object, but about the target object that the pointer is pointing to.