我要运行的函数:
struct foo;
void bar(const foo* p = 0);
我如何调用该函数:
auto thread = std::thread(&bar, NULL);
警告:
foobar.h:223:9: warning: passing NULL to non-pointer argument 2 of ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (*)(const foo*), _Args = {int}]’ [-Wconversion-null]
我在这里错过了什么?
当我使用非NULL
参数调用函数时,警告消失。
最佳答案
问题是 NULL
有点模棱两可。
虽然它在语义上是一个指针,但它可以(并且在您的实现中是)整数类型。
18.2 Types
[support.types]
3 The macro
NULL
is an implementation-defined C++ null pointer constant in this International Standard (4.10).
4.10 Pointer conversions
[conv.ptr]
1 A null pointer constant is an integer literal (2.14.2) with value zero or a prvalue of type
std::nullptr_t
.
[...]
因此您的实现决定将其设为普通 0
以实现向后兼容性,但将其标记为额外诊断。
这实际上是促进可移植代码的一个值得称赞的决定。
虽然遗憾的是没有人能跳进时间机器,只是让 NULL
与标准中的 nullptr
相同,所以歧义不存在。
要解决该错误,请使用 nullptr
而不是 NULL
,或者使用正确类型的指针,但更复杂但不太好。
关于c++ - 警告:将 NULL 传递给“std::thread::thread”的非指针参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27951344/