Markus.Elfring@web.de wrote:[color=blue]
> I am interested to know if the pointer value for the memory address can
> be changed by a compiler if the constness of the corresponding type is
> cast away.[/color]
The bits may change, but it's value can't. i.e. you can use the
equality/relational operators to compare it, but you can't use memcpy.
You can however use memmove/memcpy to copy the bits over though.
[color=blue]
> inline char* deconstify1(char const * X) { return (char*) X; }
> inline char* deconstify2(char const * X) { return const_cast<char*>(X);
> }[/color]
These two mean the exact same thing.
[color=blue]
> const char source [] = "Test";
> char* alias1 = deconstify1(source);
> char* alias2 = deconstify2(source);
>
> if ((source != alias1) || (source != alias2) || (alias1 != alias2))
> { printf("unequal: %p %p %p", source, alias1, alias2); }[/color]
I think you meant && and not ||. Even with &&, this example will always
evaluate to true. Your example doesn't even answer what you really
mean. What you really meant was:
const char source [] = "Test";
const char *p1 = source;
char *p2 = deconstify1(source);
const char *p3;
memcpy(&p3, &p2, sizeof(p2));
p1 == p3
And the answer is: yes, this is guaranteed to be true because
qualifiers only change the level of access in terms of the type system,
not the way the bits are interpreted in a pointer:
3.9.2/3 Pointers to cv-qualified and cv-unqualified versions (3.9.3) of
layout-compatible types shall have the same value representation and
alignment requirements (3.9).
^-- this is an even stronger guarantee about the representation being
the same
3.9.3/1 The cv-qualified or cv-unqualified versions of a type are
distinct types; however, they shall have the same representation and
alignment requirements (3.9).50)
3.9.3/1#50) The same representation and alignment requirements are
meant to imply interchangeability as arguments to functions, return
values from functions, and members of unions.
^-- this is extra to say that even the top level const on pointers have
the same representation, so we can change "const char *p1" to "const
char * const p1" and it will still work.
[color=blue]
> Can this happen on a current platform?
> Does any tool try to copy the data to a read-only area to achieve any
> protection?[/color]
I don't understand what you're asking. Any const object[*] is allowed
to be stored in read only memory. You can cast away constness and read
from it, but any write to that storage location results in undefined
behavior.
[*] top level consts, i.e. "int * const var" is allowed to be stored in
read only memory but "const int *var" is not.