gpt4 book ai didi

c++ - MSVC 上的 NULL 行为

转载 作者:行者123 更新时间:2023-12-02 15:46:10 25 4
gpt4 key购买 nike

我正在尝试 this代码片段

#include <cstddef>
#include <cstdio>

void f(int* ptr){
std::printf("int*\n");
}

void f(int val){
std::printf("int\n");
}

int main() {
f(NULL);
}

这在 GCC 和 CLANG 上都会出错,但 MSVC 会打印 int。根据我对 [conv.ptr] 的阅读,因为整数类型的空指针常量(NULL 是什么)可以转换为指针类型,所以在选择适当的函数时,编译器应该是有歧义的,因为它可以绑定(bind)两者到 intint*。我确认所有这些编译器都通过

NULL实现为整数类型
#if defined(_MSC_VER)
static_assert(std::is_same<decltype(NULL), int>(), "");
#else
static_assert(std::is_same<decltype(NULL), long>(), "");
#endif

那么,这是一个 MSVC 错误,还是我遗漏了什么,编译器在这种情况下不会抛出错误?

编辑:我知道 nullptr 是衡量空性的 方法,但这个问题仅仅是出于好奇并试图理解周围的规范

最佳答案

NULL是一个旧的 C 兼容性宏。它通常定义为普通整数 0。因此 f(int) 将被调用。

在 C++ 中你应该使用 nullptr对于空指针。

关于c++ - MSVC 上的 NULL 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74139477/

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