The data types the 4 different casts can take (or normally take) in c++

It seems static_cast take could take value, reference or pointer and convert them to another type of value, reference or pointer. However, it seems dynamic_cast, reinterpret_cast and const_cast can only take reference and pointer .

I know for cont_cast, it only take pointer or reference but not variable which is undefined behavior. Not sure why dynamic_cast and reinterpret_cast can only take reference and pointer and what will happen if use dynamic_cast and reinterpret_cast on value types.

For instance, static_cast take could take pointer :

B* pb; D* pd;
pointer:D* pd2 = static_cast<D*>(pb);  // Not safe, D can have fields and methods that are not in B.

For another instance, suppose dynamic_cast and reinterpret_cast take value types:

int B; char D;
B = dynamic_cast<B>(D);

int B; char D;
B = reinterpret_cast<B>(D);

What will happen and why we should not do this?


However, it is not safe for static_cast to take pointer as input

The point of static cast is that it uses compile-time information to determine if the cast is safe. So you certainly can convert pointers using static_cast:

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

int main() {
    B * bp = nullptr;
    A * ap = static_cast <A*> (bp);       // OK
    char * cp = static_cast <char*> (bp);    // error
}
链接地址: http://www.djcxy.com/p/28764.html

上一篇: 在x86汇编中将寄存器设置为零的最佳方法是什么?xor,mov或and?

下一篇: 4种不同类型的数据类型可以在c ++中采用(或通常采用)