【C++】01 四种转换:static_cast, dynamic_cast, const_cast and reinterpret_cast

link

Question:

What are the proper uses of:

  • static_cast
  • dynamic_cast
  • const_cast
  • reinterpret_cast
  • C-style cast (type)value
  • Function-style cast type(value)

How does one decide which to use in which specific cases?

Answer:

static_cast:

  static_cast is the first cast you should attempt to use. It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating static_cast isn’t necessary, but it’s important to note that the T(something) syntax is equivalent to (T)something and should be avoided (more on that later). A T(something, something_else) is safe, however, and guaranteed to call the constructor.

  static_cast can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn’t cast through virtual inheritance. It does not do checking, however, and it is undefined behavior to static_cast down a hierarchy to a type that isn’t actually the type of the object.

  ①基本类型的转换:

double f = 100.3f;
int i = (int)f;			//C风格的 隐式类型转换
int i2 = static_cast<int>(f);	//C++C+风格的转换

  ②子类转换成父类的转换:

class Father{};
class Child :public FatherP{};
int main(){
	Child b;
	Father a = static_cast<Father>b;	//子类可以转换为父类,父类不可转换为子类
}

const_cast:

  const_cast can be used to remove or add const to a variable; no other C++ cast is capable of removing it (not even reinterpret_cast). It is important to note that modifying a formerly const value is only undefined if the original variable is const; if you use it to take the const off a reference to something that wasn’t declared with const, it is safe. This can be useful when overloading member functions based on const, for instance. It can also be used to add const to an object, such as to call a member function overload.

  const_cast also works similarly on volatile, though that’s less common.

  用于去除或者添加 指针或引用 的 const 属性。换句话说,这个转换能将 const 属性转换掉,它能且只能做这样一件事情。同样属于编译的时候会进心的类型转换检查。


dynamic_cast:

  dynamic_cast is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The dynamic_cast will seek out the desired object and return it if possible. If it can’t, it will return nullptr in the case of a pointer, or throw std::bad_cast in the case of a reference.

  dynamic_cast has some limitations, though. It doesn’t work if there are multiple objects of the same type in the inheritance hierarchy (the so-called ‘dreaded diamond’) and you aren’t using virtual inheritance. It also can only go through public inheritance - it will always fail to travel through protected or private inheritance. This is rarely an issue, however, as such forms of inheritance are rare.

  dynamic_cast 应用于 运行时 类型识别和检查(与 static_cast 不一样,static_cast 是 编译时 类型检查),仅用于 父类转换成子类。因为要做类型检查,所以检查的代价很昂贵,但也保证了转换的安全性。安全的向下进行类型转换。只能用于含有虚函数的类,只能转指针或引用。


reinterpret_cast:

  reinterpret_cast is the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in an int, or all sorts of other nasty things. Largely, the only guarantee you get with reinterpret_cast is that normally if you cast the result back to the original type, you will get the exact same value (but *not* if the intermediate type is smaller than the original type). There are a number of conversions that reinterpret_cast cannot do, too. It’s used primarily for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data, or storing data in the low bits of a pointer to aligned data.

  reinterpret_cast:reinterpret 表示 重新解释、重新解读。用于处理本来没有关联的类型转换,按照转换后的类型重新解释内存中的内容。在编译的时候进行类型转换的检查。允许将任何指针转换为任何其他指针类型,并不安全。
  常常用于:①将一个整型转换成指针②一种类型的指针转换成另一种类型的指针③将一个指针类型到一个整型进行转换。


  C-style cast and function-style cast are casts using (type)object or type(object), respectively, and are functionally equivalent. They are defined as the first of the following which succeeds:

  • const_cast
  • static_cast (though ignoring access restrictions)
  • static_cast (see above), then const_cast
  • reinterpret_cast
  • reinterpret_cast, then const_cast

  It can therefore be used as a replacement for other casts in some instances, but can be extremely dangerous because of the ability to devolve into a reinterpret_cast, and the latter should be preferred when explicit casting is needed, unless you are sure static_cast will succeed or reinterpret_cast will fail. Even then, consider the longer, more explicit option.

  C-style casts also ignore access control when performing a static_cast, which means that they have the ability to perform an operation that no other cast can. This is mostly a kludge, though, and in my mind is just another reason to avoid C-style casts.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值