c++ - 警告:将 NULL 传递给“std::thread::thread”的非指针参数

标签 c++ templates c++11 perfect-forwarding nullptr

我要运行的函数:

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/

相关文章:

c++ - 我如何将其读入 Entry fname?

c++ - C/C++ : A (*eval(A (*function)(B), B b))(){ ... } 可能吗? (可能是 C++11 之前的版本)

c++ - 在运行时按索引访问 std::tuple 元素的最佳方式

c++ - 关于使用每个函数结构(参数对象)模拟 "named arguments"以获取函数调用选项的问题?

c++ - If-else 语句中的返回值 - C++

c++ - 位对齐 访问任意位长度字节对齐缓冲区

C++ 模板类的自继承

c++ - 如何隐藏来自外部库的编译警告

c++ - 为什么 decltype(*this) 没有返回正确的类型?

c++ - C++ 模板的问题(大惊喜!)。为什么这行不通?