static_cast and reference to pointers

余生长醉 提交于 2019-12-10 18:05:23

问题


Can anyone tell me why this doesn't compile:

struct A { };
struct B : public A { };

int main()
{
  B b;
  A* a = &b;
  B* &b1 = static_cast<B*&>(a);
  return 0;
}

Now, if you replace the static cast with:

B* b1 = static_cast<B*>(a);

then it does compile.

Edit: It is obvious that the compiler treats A* and B* as independent types, otherwise this would work. The question is more about why is that desirable?


回答1:


B is derived from A, but B* isn't derived from A*. A pointer to a B is not a pointer to an A, it can only be converted to one. But the types remain distinct (and the conversion can, and often will, change the value of the pointer). A B*& can only refer to a B*, not to any other pointer type.




回答2:


non-constant lvalue reference (B*&) cannot bind to a unrelated type (A*).




回答3:


You are trying to cast an A* to a B*. This is the wrong way around and not very useful. You probably want to store a pointer to derived in a pointer to base, which is useful and doesn't even need a cast.

I suppose a dynamic_cast might work here, but the result is implementation defined if I'm not mistaken.




回答4:


Handling of references is something the compiler does for you, there should be no need to cast to reference.

If we refactor the code to:

B b;
A* a = &b;
B* b_ptr = static_cast<B*>(a);
B*& p1 = b_ptr;

It will compile.



来源:https://stackoverflow.com/questions/14382730/static-cast-and-reference-to-pointers

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