简体   繁体   English

如何在C ++中实现static_cast?

[英]How is static_cast implemented in c++?

How does static_cast work? static_cast如何运作? If you are doing something like... 如果您正在做类似...

If D inherits from B via some unspecified hierarchy (not necessarily directly), and you do: 如果D通过某个未指定的层次结构(不一定直接)从B继承,则您执行以下操作:

B* b = new D();
D* d = static_cast<D*>(b);

what is happening? 怎么了? Is it simply calculating an offset at compile time and applying that offset to the pointer? 它是否只是在编译时计算偏移量并将该偏移量应用于指针? Or is there something happening at runtime in order to do the cast? 还是在运行时发生某些事情以进行转换?

what is happening? 怎么了?

The compiler assumes that you know what you're doing, so that the pointer really does point to a D object, and changes the pointer type accordingly, adjusting the value if necessary to point to the complete D object rather than the B sub-object. 编译器假定您知道自己在做什么,因此指针确实确实指向了D对象,并相应地更改了指针类型,并在必要时调整了值以指向完整的D对象而不是B子对象。 。

If you get it wrong, and use a D* pointer that doesn't really point to a D object, then you'll get undefined behaviour; 如果弄错了,并使用了一个D*指针,该指针实际上并没有指向D对象,那么您将获得未定义的行为。 so be careful. 所以要小心

Is it simply calculating an offset at compile time and applying that offset to the pointer? 它是否只是在编译时计算偏移量并将该偏移量应用于指针?

Yes. 是。

Or is there something happening at runtime in order to do the cast? 还是在运行时发生某些事情以进行转换?

No; 没有; "static" implies that it uses only compile-time information. “静态”表示仅使用编译时信息。 The only runtime activity is adding the fixed offset if necessary. 必要时,唯一的运行时活动是添加固定偏移量。

Use dynamic_cast if you want a runtime check that the conversion is valid (as long as the types are polymorphic). 如果要运行时检查转换是否有效(只要类型是多态的),请使用dynamic_cast It will give a null pointer (or throw a bad_cast exception if you're casting a reference rather than a pointer) if there isn't really a D object there. 如果那里没有真正的D对象,它将提供一个空指针(或者,如果您要投射引用而不是指针,则抛出bad_cast异常)。

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

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