以下是一些值得注意的事情:
- 在"C95"(ISO C 9899:1990的增编)中增加了
__STDC__
和__STDC_VERSION__
.
- 您不能使用预处理器条件判断
nullptr
,因为它不是宏.
- 即使在使用符合要求的C23编译器时,用户也可能忘记包含
stddef.h
或等效头文件,所以不要假设这个是#Included.
- 当前版本的GCC和clang支持
-std=c2x
,其中包含nullptr
,但将__STDC_VERSION__
设置为占位符值202000L.
- 并非所有版本的C++都包含
nullptr
,因为它是在C++11中添加的.
因此,宏判断应如下所示:
/* C++11 or later? */
#if (defined(__cplusplus) && __cplusplus >= 201103L)
#include <cstddef>
/* C2x/C23 or later? */
#elif ( defined(__STDC__) && \
defined(__STDC_VERSION__) && \
(__STDC_VERSION__ >= 202000L) )
#include <stddef.h> /* nullptr_t */
/* pre C23, pre C++11 or non-standard */
#else
#include <stddef.h> /* NULL */
#define nullptr NULL
typedef void* nullptr_t;
#endif