是否有任何主要的 C++ 实现实际上将“NULL”定义为“nullptr”?

2023-12-29

从 C++11 开始,标准允许宏NULL要么是一个值为零的整数文字,要么是类型的纯右值std::nullptr_t.

任何决定更改其定义的标准库供应商NULL从一个整数到nullptr很可能会导致依赖 C++11 之前代码的客户端崩溃。

是否有任何主要实现(例如 GCC、Clang、MSVC)实际上定义了NULL as nullptr?或者,尽管有这种可能性,却没有人这样做?


libstdc++ 依赖于包括stddef.h https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/include/c/cstddef#L34-L38,它定义了NULL通过以下方式:

// <stddef.h>
//
#if defined (_STDDEF_H) || defined (__need_NULL)
#undef NULL     /* in case <stdio.h> has defined it. */
#ifdef __GNUG__
#define NULL __null
#else   /* G++ */
#ifndef __cplusplus
#define NULL ((void *)0)
#else   /* C++ */
#define NULL 0
#endif  /* C++ */
#endif  /* G++ */
#endif  /* NULL not defined and <stddef.h> or need NULL.  */
#undef  __need_NULL

相关信息__null可以在这个问题 https://stackoverflow.com/questions/8783566/where-is-null-defined-in-g:

实施__null是作为 G++ 内部的。基本上,内部做了你天真的期望的事情reinterpret_cast<void *>(0) to do.

它的类型是“魔法”,具体取决于上下文。这就是 G++ 必须将其实现为内部的原因。没有任何常规类型可以提供精确正确的语义。它的作用大致类似于void *,但不完全是。


libc++ 做几乎同样的事情 https://github.com/llvm-mirror/libcxx/blob/master/include/cstddef#L43-L45:

// <cstddef>
//
// Don't include our own <stddef.h>; we don't want to declare ::nullptr_t.
#include_next <stddef.h>
#include <__nullptr>

微软的STL also 依赖于包括stddef.h https://github.com/microsoft/STL/blob/master/stl/inc/cstddef#L12:

#pragma once
#ifndef _CSTDDEF_
#define _CSTDDEF_
#include <yvals_core.h>
#if _STL_COMPILER_PREPROCESSOR

#include <stddef.h>

我找不到stddef.h在开源 STL 存储库中,但是定义NULL提供于vcruntime.h:

#ifndef NULL
    #ifdef __cplusplus
        #define NULL 0
    #else
        #define NULL ((void *)0)
    #endif
#endif

一个简单的测试icc 19.0.1还表明NULL不定义为nullptr:

#include <type_traits>
#include <cstddef>

static_assert(!std::is_same<decltype(NULL), std::nullptr_t>::value, "");
static_assert(!std::is_same<decltype(NULL), int>::value, "");
static_assert(std::is_same<decltype(NULL), long>::value, "");

住在 godbolt.org 上 https://gcc.godbolt.org/z/MQ55aQ

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否有任何主要的 C++ 实现实际上将“NULL”定义为“nullptr”? 的相关文章

随机推荐