static_cast'd pointer value

孤街醉人 提交于 2019-12-01 03:33:26

You may misunderstand the term "pointer value". The term is defined in [basic.compound]/3:

Every value of pointer type is one of the following:

  • a pointer to an object or function (the pointer is said to point to the object or function), or

  • a pointer past the end of an object ([expr.add]), or

  • the null pointer value ([conv.ptr]) for that type, or

  • an invalid pointer value.

A value of a pointer type that is a pointer to or past the end of an object represents the address of the first byte in memory ([intro.memory]) occupied by the object or the first byte in memory after the end of the storage occupied by the object, respectively.

So you can see the term "pointer value" in the standard is a very abstract term. Even if two pointer values represent the same address, they may have different values. The example in cppreference demonstrates the concept of "pointer value" nicely:

struct S1 { int a; } s1;
struct S2 { int a; private: int b; } s2; // not standard-layout
union U { int a; double b; } u = {0};
int arr[2];

int* p1 = reinterpret_cast<int*>(&s1); // value of p1 is "pointer to s1.a" because s1.a
                                       // and s1 are pointer-interconvertible

int* p2 = reinterpret_cast<int*>(&s2); // value of p2 is unchanged by reinterpret_cast and
                                       // is "pointer to s2". 

int* p3 = reinterpret_cast<int*>(&u);  // value of p3 is "pointer to u.a": u.a and u are
                                       // pointer-interconvertible

double* p4 = reinterpret_cast<double*>(p3); // value of p4 is "pointer to u.b": u.a and u.b
                                            // are pointer-interconvertible because both
                                            // are pointer-interconvertible with u

int* p5 = reinterpret_cast<int*>(&arr); // value of p5 is unchanged by reinterpret_cast and
                                        // is "pointer to arr"
bolov

Is there a case, when casting a void * to something pointer-interconvertible actually changes the pointer value?

No, the standard clearly states

If two objects are pointer-interconvertible, then they have the same address

What is the intent of this distinction?

I would think the distinction comes not in the value of the pointer but in it's semantics. The important part is that you end up with a pointer to the object b (which inter-covertible with the original object pointed). This is a stronger and more specific guarantee than "the original value remains unchanged", even though in this case the original value also remains unchanged.

Stronger guarantee: the resulting pointer points to an actual object (not just to an address in memory)

A more specific guarantee: this object is specified: it is the object b which is pointer interchangeable with the original object pointed by the pointer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!