c++ - 为什么使用 <cheader> 而不是 &lt;header.h>?

标签 c++ namespaces header-files

<分区>

我一直认为如果你这样做 #include <cheader> (其中 header 是一些标准的 c++ 头文件,如 stdio/stdlib/string),它与 #include <header.h> 相同, 但包裹在 std 中命名空间。那么该代码片段如何编译 (g++ 4.7.3)?

#include <cstdlib>
int main()
{
    malloc(1);
    return 0;
}

为什么要包括 <cstdio>那么(而不是 <stdio.h> )标准 C 函数是否仍然位于全局命名空间中?

第二个问题是——我应该怎么做才能从全局命名空间中获取其中一些函数(同时使用 C++ 头文件)?例如,我不想要 malloc在全局命名空间中,因为我有一个 home 分配:编写我自己的内存分配器(特别是 mallocfree 函数),我将编译到动态库中并使用 LD_PRELOAD 插入任何程序.

最佳答案

How does that code snippet compiles then (g++ 4.7.3)?

因为 C++11 标准的 17.6.1.2/4 规定:

[...] It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations (7.3.3).

因此,允许实现在全局命名空间中定义这些实体。

Why should one include then (instead of ) if standard C functions will be in the global namespace anyway?

首先,作为一个良好的风格问题。包括<stdio.h>让您确定所有实体都在全局命名空间中定义,同时包括 <cstdio>让您确定这些实体位于您想要的位置(在 std 命名空间中),可能(但不确定)不必要的缺点是这些名称也可能出现在全局命名空间中。

what should I do to get some of these functions out of the global namespace (while using c++ headers at the same time)?

不幸的是,您无法从实体所在的命名空间中获取实体。但是您可以做的(除了诅咒您的实现)是完全避免使用标准 C 函数,而更喜欢使用C++ 标准库中的函数。这些保证住在std命名空间。

例如,如果您必须执行低级内存管理,请使用 new运算符而不是 malloc .此外,请注意对“必须”的强调:大多数时候,您应该使用 RAII 包装器,例如智能指针或标准容器,以避免不得不应对低级内存管理,new , 和 delete完全没有。

关于c++ - 为什么使用 <cheader> 而不是 &lt;header.h>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16771879/

相关文章:

c++ - 错误 0x8004100e 连接到 WMI 命名空间

python - 通过API调用xbacklight

ruby-on-rails - 哪个更适合 Rails 站点?/{login} 或/user/{login}

c++ - CMake 可以找到一个 Boost 头文件,但找不到另一个

c++ - g++ 找不到 header ,但我确实包含了它们

c++ - wxwidget with MinGW [编译/链接到 wxmsw26ud_core ]

c++ - 如何在 C++ 中将 typedef 与类初始值设定项参数一起使用?

c++ - 我需要/如何释放 wstring、wstringstream、 vector

xml - 使用 CSS 选择器解析 Perl XML

c++ - 如何在声明和定义中拆分静态 lambda?