c – 我应该使用它还是static_cast然后使用static_cast来避免reinterpret_cast?

前端之家收集整理的这篇文章主要介绍了c – 我应该使用它还是static_cast然后使用static_cast来避免reinterpret_cast?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我见过人们建议使用static_cast< SomeType *>(static_cast< void *>(p))而不是重新解释强制转换. @H_502_2@我不明白为什么这样更好,有人可以解释一下吗?

@H_502_2@为了论证,这里是一个需要reinterpret_cast的示例场景:

DWORD lpNumberOfBytes;
ULONG_PTR lpCompletionKey;
LPOVERLAPPED lpOverlapped;
GetQueuedCompletionStatus(myHandle,&lpNumberOfBytes,&lpCompletionKey,&lpOverlapped,0);
if(lpCompletionKey == myCustomHandlerKey){
    auto myObject = reinterpret_cast<MyObject*>(lpOverlapped);  //i know this is really a MyObject
}
@H_502_2@这是我听到的建议:

auto myObject = static_cast<MyObject*>(static_cast<void*>(lpOverlapped));
@H_502_2@编辑:我原本开始我的问题在评论部分“asdf”建议在这里使用static_cast而不是reinterpret_cast http://blogs.msdn.com/b/vcblog/archive/2014/02/04/challenge-vulnerable-code.aspx,但回想起我的问题来自那里的事实是无关紧要的.

解决方法

§5.2.10描述了reinterpret_cast可以执行的合法映射,并指定“不能执行其他转换”. @H_502_2@与您的示例相关的转换是/ 7:

@H_502_2@A pointer to an object can be explicitly converted to a pointer to a different object type. When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”,the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types … and the alignment requirements of T2 are no stricter than those of T1. [emphasis mine]

@H_502_2@任何其他指向对象类型的指针的转换结果是“未指定”.1

@H_502_2@这是reinterpret_cast危险的两个原因之一:它的转换仅为指向对象类型的指针子集定义良好,编译器通常不提供有关意外误用的诊断.

@H_502_2@第二个原因是编译器甚至不检查您尝试执行的映射是否合法,以及将执行多个(语义上完全不同的)映射中的哪一个.

@H_502_2@最好明确并告诉编译器(和读者)您想要执行的转换.也就是说,asdf的评论不太正确,因为并非您通过reinterpret_cast执行的所有转换都等同于使用static_cast< void *>然后是static_cast到目标类型.

@H_502_2@1旁白:简而言之(略微简化),“standard layout type”是一种类型(或类型数组),它没有虚函数或混合成员可见性,其所有成员和基础也是标准布局.类型的alignment是对它可能位于的存储器中的地址的限制.例如,许多机器要求双精度在可被8整除的地址处对齐.

原文链接:https://www.f2er.com/c/110329.html

猜你在找的C&C++相关文章