Is there an actual difference between a const_cast and c style cast (ObjectType) ?
6 回答
A const_cast
conveys specific information about the intent behind the cast that a C cast cannot.
If you accidentally try to use a const_cast
for purposes other than adding or removing const
or volatile
, the compiler will help you with an error message.
Also, const_cast
is searchable, unlike a C-style cast.
Aconst_cast
只能添加或删除const
-ness(或volatile
-ness,尽管这不太常见)。
C 风格的演员表可以做与任何“新”演员表相同的事情,除了 a dynamic_cast
(它可以做一些他们都做不到的事情,尽管它在这里并不真正相关)。
C-style cast in C++ attempts a static cast, a reinterpret cast, a const cast, or a combination of those.
It is recommended to avoid C casts mainly because...
- reinterpret casts and const casts are used seldomly enough that it's good to emphasize what you're doing,
- in other cases, when you want a static cast, writing it explicitly gives you additional compile-time checks compared to C casts.
const_cast
只能修改参数的const-ness(或volatile-ness),而不是它的基本类型。所以
const T *tc = f();
volatile T *tv = g();
U *ua = const_cast<U*>(tc); //error
U *ub = const_cast<U*>(tv); //error
U *ub = (U*)(tc); //okay
U *ub = (U*)(tv); //okay
所以 c-style cast 修改 cv-qualifiedT*
到U*
没有任何问题。
一样的动作。C 风格的强制转换可以完全抛弃 const。
const_cast 的原因是它可以作为一个可搜索的红旗,可以搜索并仔细审查/惩罚有罪的人。这个想法是 C++ 比 C 更加类型紧密。因此,如果不是不可能的话,故意违反类型系统(例如违反 const 正确性)很容易被发现。
使这种违反类型安全的行为完全不可能会破坏太多的向后兼容性。
const_cast 受到更多限制,除了更改 const-ness 之外,不会让您做任何事情。这使它更安全,即不易发生事故。
此外,它更容易搜索。