2012年7月25日星期三

static_cast vs reinterpret_cast vs dynamic_cast


static_cast vs reinterpret_cast vs dynamic_cast


> static_cast

  用法:static_cast<type-id> (expression)
  该运算符把expression转换为type-id类型,但没有运行时类型检查来保证转换的安全性。它主要有如下几种用法:
  用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换。
  进行上行转换(把派生类的指针或引用转换成基类表示)是安全的;
  进行下行转换(把基类指针或引用转换成派生类表示)时,由于没有动态类型检查,所以是不安全的。
  用于基本数据类型之间的转换,如把int转换成char,把int转换成enum。这种转换的安全性也要开发人员来保证。
  把空指针转换成目标类型的空指针。
  把任何类型的表达式转换成void类型。
  注意:static_cast不能转换掉expressionconstvolatile、或者__unaligned属性。
  C++static_castreinterpret_cast的区别
  C++primer第五章里写了编译器隐式执行任何类型转换都可由static_cast显示完成;reinterpret_cast通常为操作数的位模式提供较低层的重新解释
  1C++中的static_cast执行非多态的转换,用于代替C中通常的转换操作。因此,被做为隐式类型转换使用。比如:
  int i;
  float f = 166.7f;
  i = static_cast<int>(f);
  此时结果,i的值为166
  2C++中的reinterpret_cast主要是将数据从一种类型的转换为另一种类型。所谓通常为操作数的位模式提供较低层的重新解释也就是说将数据以二进制存在形式的重新解释。比如:
  int i;
  char *p = "This is a example.";
  i = reinterpret_cast<int>(p);
  此时结果,ip的值是完全相同的。reinterpret_cast的作用是说将指针p的值以二进制(位模式)的方式被解释为整型,并赋给i//i 也是指针,整型指针;一个明显的现象是在转换前后没有数位损失。
 ==================================================

reinterpret_cast
  用法:reinterpret_cast<type-id> (expression)
       reinterpret_cast是为了映射到一个完全不同类型的意思,这个关键词在我们需要把类型映射回原有类型时用到它。我们映射到的类型仅仅是为了故弄玄虚和其他目的,这是所有映射中最危险的。 (这句话是 C++编程思想中的原话 )
  static_cast reinterpret_cast的区别主要在于多重继承,比如
  class A { public: int m_a; };
  class B { public: int m_b; };
  class C : public A, public B {};
  那么对于以下代码:
  C c;
  printf("%p, %p, %p\r\n", &c, reinterpret_cast<B*>(&c), static_cast <B*>(&c));
  前两个的输出值是相同的,最后一个则会在原基础上偏移 4个字节,这是因为 static_cast计算了父子类指针转换的偏移量,并将之转换到正确的地址( c里面有 m_a,m_b,转换为 B*指针后指到 m_b处),而 reinterpret_cast却不会做这一层转换。
  因此你需要谨慎使用 reinterpret_cast。

 >> reinterpret_cast 特殊用途
使用reinterpret_cast关键字的一个特殊用途,用于C++实现哈希函数的数值转换。(该数值转换即类C(语言)的强制转换,不安全性。) msdn上面示例说明如下:

One practical use of 
reinterpret_cast is in a hash function, which maps a value to an index in such a way that two distinct values rarely end up with the same index.

// expre_reinterpret_cast_Operator.cpp
// compile with: /EHsc
#include <iostream>

// Returns a hash code based on an address
unsigned short Hash( void *p ) {
   unsigned int val = reinterpret_cast<unsigned int>( p );
   return ( unsigned short )( val ^ (val >> 16));
}

using namespace std;
int main() {
   int a[20];
   for ( int i = 0; i < 20; i++ )
      cout << Hash( a + i ) << endl;
}
The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function.

dynamic_cast
用法:dynamic_cast<type-id> (expression)
dynamic_cast把expression转换成type-id类型的对象。Type-id必须是类的指针、类的引用或者void*;
如果type-id是类指针类型,那么expression也必须是一个指针,如果type-id是一个引用,那么expression也必须是一个引用。
dynamic_cast运算符可以在执行期决定真正的类型。如果downcast是安全的(也就说,如果基类指针或者引用确实指向一个派生类对象)这个运算符会传回适当转型过的指针。如果downcast不安全,这个运算符会传回空指针(也就是说,基类指针或者引用没有指向一个派生类对象)。
dynamic_cast主要用于类层次间的上行转换和下行转换,还可以用于类之间的交叉转换。
在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;
在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全。

基类中要有虚函数,否则使用dynamic_cast会编译出错,而static_cast则没有这个限制。
因为基类中存在虚函数,就说明它有想要让基类指针或引用指向派生类对象的情况,此时dynamic_cast转换才有意义。
这是由于运行时类型检查需要运行时类型信息,而这个信息存储在类的虚函数表(关于虚函数表的概念,详细可见<Inside c++ object model>)中,只有定义了虚函数的类才有虚函数表,没有定义虚函数的类是没有虚函数表的。
另外,dynamic_cast还支持交叉转换(cross cast)

dynamic_cast操作失败的情况,其返回值根据type-id类型不同,
1. type-id为指针类型,则返回NULL空指针。
2. type-id为引用类型,则抛出一个bad_cast异常。
---
When dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown instead.


dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).
---

> const_cast


以上内容整理了C++语言的几种类型转换的用法、说明以及使用时注意点,包括static_cast vs reinterpret_cast vs dynamic_cast。唯一确少的const_cast,它是用于常量与非常量之间的类型转换,对其理解与使用相对比较简单,所以可忽略提及,可参加cppreference百度百科

> 参考资料
该文章源自于网站资料的收集与整理,参考资料引用自:
1.  Type Casting from cplusplus。
2.static_cast 百度百科
3. reinterpret_cast cppreferencemsdn
4. dynamic_cast 百度百科msdn






没有评论:

发表评论