简体   繁体   English

static_cast和对指针的引用

[英]static_cast and reference to pointers

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. 编辑:很明显,编译器将A*B*视为独立类型,否则这将起作用。 The question is more about why is that desirable? 问题更多的是为什么这是可取的?

B is derived from A , but B* isn't derived from A* . B来自A ,但B*不是来自A* A pointer to a B is not a pointer to an A , it can only be converted to one. 指向B的指针不是指向A的指针,它只能转换为一个指针。 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. A B*&只能引用B* ,而不能引用任何其他指针类型。

非常量左值引用(B *&)不能绑定到不相关的类型(A *)。

You are trying to cast an A* to a B* . 您正在尝试将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. 您可能希望将指针存储在指向base的指针中,这很有用,甚至不需要强制转换。

I suppose a dynamic_cast might work here, but the result is implementation defined if I'm not mistaken. 我想动态dynamic_cast可能在这里工作,但如果我没有弄错的话,结果就是定义的实现。

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. 它会编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM