【发布时间】:2021-11-24 07:34:42
【问题描述】:
我知道有类似的问题,但我不知道这个问题的最佳措辞。
我觉得有点讽刺的是,代码分析警告的原因首先是它告诉我在两个实例中使用gsl::narrow:
实例 1:
auto* pCell1 = gsl::narrow<CGridCellBase*>(lParam1);
auto* pCell2 = gsl::narrow<CGridCellBase*>(lParam2);
编译错误:
6>D:\My Libraries\GSL-main\include\gsl\util(105,1): error C2440: 'static_cast': cannot convert from 'U' to 'T'
6> with
6> [
6> U=LPARAM
6> ]
6> and
6> [
6> T=CGridCellBase *
6> ]
6>D:\My Libraries\GSL-main\include\gsl\util(105,12): message : Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
实例 2:
auto* pItem = gsl::narrow<NM_GRIDVIEW*>(pNotifyStruct);
编译错误:
6>D:\My Libraries\GSL-main\include\gsl\narrow(58,1): error C2440: 'static_cast': cannot convert from 'const T' to 'U'
6> with
6> [
6> T=NM_GRIDVIEW *
6> ]
6> and
6> [
6> U=NMHDR *
6> ]
6>D:\My Libraries\GSL-main\include\gsl\narrow(58,9): message : Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
那些消息告诉我做相反的事情:
- 从整数类型转换为指针类型需要 reinterpret_cast、C 样式转换或函数样式转换
- 指向的类型不相关;转换需要 reinterpret_cast、C-style cast 或 function-style cast
绕圈子!鉴于当时的情况,我是否理解正确的前进方向是:
- 使用
reinterpret_cast和... - 添加适当的
prama警告以抑制警告。
正确吗?
【问题讨论】:
-
很抱歉我没有完全遵循,特别是关于绕圈子。
static_cast的功能受到限制(在某种程度上它是“安全的”)。两种转换都不是“编译时检查正确”,因此您不能使用static_cast,错误消息会告诉您可以使用哪些转换。 -
@MicroVirus 平心而论,原始代码是 C 风格的。警告建议 gsl::narrow 等。但我已更改为 reinterpret_cast 和 pragma 抑制。
-
或者...自己动手
pointer_cast(视频下文)? -
@AdrianMole Myown
pointer_cast?以前从来没有这样做过!!!!!!
标签: visual-c++ code-analysis reinterpret-cast cpp-core-guidelines