Should I use static_cast or reinterpret_cast when casting a void* to whatever(我应该在将 void* 转换为任何内容时使用 static_cast 还是 reinterpret_cast)
问题描述
static_cast 和 reinterpret_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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我应该在将 void* 转换为任何内容时使用 static_c
				
        
 
            
        基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 常量变量在标题中不起作用 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				