Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

c++ - 什么时候应该使用static_cast,dynamic_cast,const_cast和reinterpret_cast?(When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?)

What are the proper uses of:

(的正确用法是:)

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

    (C样式转换(type)value)

  • Function-style cast type(value)

    (函数样式转换type(value))

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

(如何决定在特定情况下使用哪个?)

  ask by e.James translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

static_cast is the first cast you should attempt to use.

(static_cast是您应该尝试使用的第一个演员表。)

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).

(它的作用类似于类型之间的隐式转换(例如intfloat或指向void*指针),它还可以调用显式转换函数(或隐式函数)。)

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).

(在许多情况下,无需明确声明static_cast ,但必须注意, T(something)语法与(T)something等效,应避免使用(稍后会详细介绍)。)

A T(something, something_else) is safe, however, and guaranteed to call the constructor.

(T(something, something_else)是安全的,并且保证可以调用构造函数。)

static_cast can also cast through inheritance hierarchies.

(static_cast也可以通过继承层次结构进行static_cast 。)

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.

(向上(朝向基类)进行强制转换时没有必要,但是向下转换时只要不通过virtual继承进行转换就可以使用。)

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.

(但是,它不进行检查,并且将层次结构static_cast降低为实际上不是对象类型的类型是未定义的行为。)


const_cast can be used to remove or add const to a variable;

(const_cast可用于将const删除或添加到变量;)

no other C++ cast is capable of removing it (not even reinterpret_cast ).

(没有其他C ++强制转换能够将其删除(甚至不能reinterpret_cast )。)

It is important to note that modifying a formerly const value is only undefined if the original variable is const ;

(重要的是要注意,仅当原始变量为const ,才可以修改以前的const值;)

if you use it to take the const off a reference to something that wasn't declared with const , it is safe.

(如果使用它来使const脱离对未使用const声明的内容的引用,则这是安全的。)

This can be useful when overloading member functions based on const , for instance.

(例如,这在基于const重载成员函数时很有用。)

It can also be used to add const to an object, such as to call a member function overload.

(它还可以用于向对象添加const ,例如调用成员函数重载。)

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

(const_castvolatile上也类似地工作,尽管这种情况不太常见。)


dynamic_cast is exclusively used for handling polymorphism.

(dynamic_cast仅用于处理多态。)

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.

(dynamic_cast将查找所需的对象,并在可能的情况下将其返回。)

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.

(如果不能,则在使用指针的情况下将返回nullptr ,在使用引用的情况下将返回std::bad_cast 。)

dynamic_cast has some limitations, though.

(dynamic_cast有一些限制。)

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.

(如果继承层次结构中有多个相同类型的对象(所谓的“可怕的钻石”),并且您没有使用virtual继承,则该方法将无效。)

It also can only go through public inheritance - it will always fail to travel through protected or private inheritance.

(它也只能进行公共继承-它将始终无法通过protected继承或private继承。)

This is rarely an issue, however, as such forms of inheritance are rare.

(但是,这很少有问题,因为这种继承形式很少。)


reinterpret_cast is the most dangerous cast, and should be used very sparingly.

(reinterpret_cast是最危险的强制类型转换,应谨慎使用。)

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.

(它将一种类型直接转换为另一种类型-例如将值从一个指针转换为另一种指针,或将指针存储在int或其他各种讨厌的东西中。)

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).

(在很大程度上,只有保证你得到reinterpret_cast是,通常,如果你把结果返回到原来的类型,你会得到的值完全相同( 如果中间型比原来的类型更小)。)

There are a number of conversions that reinterpret_cast cannot do, too.

(reinterpret_cast也无法完成许多转换。)

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.

(它主要用于特别奇怪的转换和位操作,例如将原始数据流转换为实际数据,或将数据存储在指向对齐数据的指针的低位。)


C-style cast and function-style cast are casts using (type)object or type(object) , respectively, and are functionally equivalent.

(C样式转换和函数样式转换分别是使用(type)objecttype(object)进行的转换,并且在功能上等效。)

They are defined as the first of the following which succeeds:

(它们被定义为以下成功的第一个:)

  • const_cast
  • static_cast (though ignoring access restrictions)

    (static_cast (尽管忽略访问限制))

  • static_cast (see above), then const_cast

    (static_cast (请参见上文),然后是const_cast)

  • reinterpret_cast
  • reinterpret_cast , then const_cast

    (reinterpret_cast ,然后是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.

(因此,在某些情况下,它可以替代其他类型的转换,但是由于有能力降级到reinterpret_cast ,因此非常危险,并且在需要显式转换时应首选后者,除非您确定static_cast将成功或reinterpret_cast将失败。)

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.

(C样式强制转换在执行static_cast时也会忽略访问控制,这意味着它们具有执行其他强制转换无法执行的操作的能力。)

This is mostly a kludge, though, and in my mind is just another reason to avoid C-style casts.

(但是,这主要是一种争执,在我看来,这是避免使用C样式强制转换的另一个原因。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...