我应该为 size_t 包含 stddef.h 还是 cstddef

当我想在 C++ 中使用 size_t 时,我应该包含 <stddef.h> 还是 ?我听过几个人说 <cstddef> 是个坏主意,应该弃用它.这是为什么呢?

When I want to use size_t in C++, should I include <stddef.h> or <cstddef>? I have heard several people saying that <cstddef> was a bad idea, and it should be deprecated. Why is that?

推荐答案

我更喜欢#include <stddef.h>.

C 头文件中的某些名称允许为宏,但设置与 C 规则不同.在 C 语言中,EXIT_FAILUREisdigit()getc() a.o.是宏.你知道哪些是 C++ 中的宏吗?

Some of the names in the C headers are allowed to be macros, but the set differs from the C rules. In C, EXIT_FAILURE, isdigit(), getc() a.o. are macros. Do you know which ones are macros in C++?

其次,只有几个标准的 C 头文件需要有 <cfoo> 头文件,而 Posix 头文件则不需要.您知道哪些标头是标准的,哪些仅由您的编译器提供?

Secondly, only a couple standard C headers are required to have the <cfoo> header, Posix headers are not. Do you know which headers are standard and which ones are provided by your compiler only?

第三,当使用来自第三方 C 库的头文件时,你最终会得到 #include <stddef.h>,我不喜欢混用 <stddef.h><cstddef>.

Thirdly, when using headers from a third-party C library, you will end up with #include <stddef.h>, and I prefer not to mix <stddef.h> and <cstddef>.

第四,新 C++ 标准的当前草案规定 <cstdlib> 允许将符号转储到全局命名空间中(因为显然现在许多编译器已经这样做了),所以使用 #include <cstdlib> 不能保证全局命名空间将来不会受到污染.所以我建议在编写可移植代码时,你应该假设全局命名空间会受到影响(即使现在不允许这样做).由于似乎只有少数专家知道这一点(请参阅此处评论中的讨论),最好使用 <stddef.h> 因为即使是 C++ 初学者也会明白它会污染全局命名空间.

Fourthly, the current draft for the new C++ standard says that <cstdlib> is allowed to dump the symbols into the global namespace (because apparently many compilers already do so nowadays), so using #include <cstdlib> is not a guarantee that the global namespace will be unpolluted in the future. So I would advice that when writing portable code, you should assume the global namespace will be affected (even though it is not allowed now). As only a few experts seem to know this (see the discussion in the comments here), it is better to use <stddef.h> as even a beginning C++ programmer will understand that it pollutes the global namespace.

相关文章