我用3个编译器测试了以下代码,得到了3个不同的结果:错误,警告和确定 .
-
GCC(5.3):错误:从'std :: nullptr_t'到'const Thing&'的用户定义转换无效
-
Clang(3.8):警告:将nullptr常量隐式转换为'bool'
-
MSVC(14.1):没有错误,没有警告
哪个编译器正确?我知道这是指针类型和 bool
之间的微不足道的转换 . 但是 std::nullptr_t
和 bool
是什么?
(最后,Clang和MSVC对代码都很好.Clang以积极的方式更加冗长 . )
struct Thing
{
Thing(bool) {}
};
void addThing(const Thing&){}
int main()
{
addThing(nullptr); // warning or error on this line
}
1 回答
这是无效的 . 根据boolean conversions的规则:
来自标准的报价,§7.14/1 Boolean conversions [conv.bool]
转换仅允许direct-initialization,但不允许copy-intialization,其中包括通过值将参数传递给函数的情况 . 例如
所以GCC是正确的 . 但是Clang也没错;标准只要求编译器在程序格式错误时“发出诊断”,因此它必须告诉您发生的事情,之后它可以做任何事情 .
见Does the C++ standard specify that for some cases the compiling should fail with an error?