我应该在将 void* 转换为任何内容时使用 static_cast 还是 reinterpret_cast

2023-02-13C/C++开发问题
3

本文介绍了我应该在将 void* 转换为任何内容时使用 static_cast 还是 reinterpret_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

static_castreinterpret_cast 似乎都可以很好地将 void* 转换为另一种指针类型.是否有充分的理由偏爱其中一个?

Both static_cast and reinterpret_cast seem to work fine for casting void* to another pointer type. Is there a good reason to favor one over the other?

推荐答案

使用 static_cast:它是最窄的强制转换,准确地描述了此处进行的转换.

Use static_cast: it is the narrowest cast that exactly describes what conversion is made here.

有一种误解,认为使用 reinterpret_cast 会更好,因为它意味着完全忽略类型安全,只是从 A 转换到 B".

There’s a misconception that using reinterpret_cast would be a better match because it means"completely ignore type safety and just cast from A to B".

然而,这实际上并没有描述 reinterpret_cast 的效果.相反,reinterpret_cast 有多种含义,因为所有这些含义都认为reinterpret_cast 执行的映射是实现定义的."[5.2.10.3]

However, this doesn’t actually describe the effect of a reinterpret_cast. Rather, reinterpret_cast has a number of meanings, for all of which holds that "the mapping performed by reinterpret_cast is implementation-defined." [5.2.10.3]

但是在从 void* 转换到 T* 的特殊情况下,映射完全由标准定义;即,在不改变其地址的情况下为无类型指针分配类型.

But in the particular case of casting from void* to T* the mapping is completely well-defined by the standard; namely, to assign a type to a typeless pointer without changing its address.

这是选择 static_cast 的原因.

此外,可以说更重要的是,reinterpret_cast 的每次使用都是彻头彻尾的危险,因为它实际上将任何东西转换为其他任何东西(对于指针),而 static_cast限制更多,从而提供更好的保护水平.这已经让我避免了错误,因为我不小心试图将一种指针类型强制转换为另一种类型.

Additionally, and arguably more important, is the fact that every use of reinterpret_cast is downright dangerous because it converts anything to anything else really (for pointers), while static_cast is much more restrictive, thus providing a better level of protection. This has already saved me from bugs where I accidentally tried to coerce one pointer type into another.

这篇关于我应该在将 void* 转换为任何内容时使用 static_cast 还是 reinterpret_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6