gpt4 book ai didi

c++ - nullptr 可以转换为 uintptr_t 吗?不同的编译器不同意

转载 作者:行者123 更新时间:2023-12-01 12:05:53 27 4
gpt4 key购买 nike

考虑这个程序:

#include <cstdint>
using my_time_t = uintptr_t;

int main() {
const my_time_t t = my_time_t(nullptr);
}

使用 msvc v19.24 编译失败:
<source>(5): error C2440: '<function-style-cast>': cannot convert from 'nullptr' to 'my_time_t'
<source>(5): note: A native nullptr can only be converted to bool or, using reinterpret_cast, to an integral type
<source>(5): error C2789: 't': an object of const-qualified type must be initialized
<source>(5): note: see declaration of 't'

Compiler returned: 2

但是 clang (9.0.1) 和 gcc (9.2.1) “吃”了这段代码,没有任何错误。

我喜欢 MSVC 的行为,但是否符合标准?
换句话说,它是 clang/gcc 中的错误还是可以解释
标准,这是来自 gcc/clang 的正确行为?

最佳答案

在我看来,MSVC 的行为不符合标准。

我的这个答案基于 C++17(草案 N4659),但 C++14 和 C++11 有相同的措辞。
my_time_t(nullptr)是一个后缀表达式,因为 my_time_t是一种类型和 (nullptr)是带括号的初始化列表中的单个表达式,它完全等同于显式转换表达式。 ( [expr.type.conv]/2 )

显式转换会尝试一些不同的特定 C++ 转换(带扩展),特别是 reinterpret_cast . ( [expr.cast]/4.4 ) 之前尝试过的类型转换 reinterpret_castconst_caststatic_cast (带有扩展和组合),但这些都不能转换 std::nullptr_t到整数类型。

但是reinterpret_cast<my_time_t>(nullptr)应该成功,因为 [expr.reinterpret.cast]/4表示 std::nullptr_t 类型的值可以像通过 reinterpret_cast<my_time_t>((void*)0) 一样转换为整数类型,这是可能的,因为 my_time_t = std::uintptr_t应该是一个足够大的类型来表示所有的指针值,在这种情况下,相同的标准段落允许转换 void*到整数类型。

特别奇怪的是,如果使用强制转换符号而不是函数符号,MSVC 确实允许转换:

const my_time_t t = (my_time_t)nullptr;

关于c++ - nullptr 可以转换为 uintptr_t 吗?不同的编译器不同意,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60507186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com