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