我一直认为如果你这样做 #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 分配:编写我自己的内存分配器(特别是 malloc
和 free
函数),我将编译到动态库中并使用 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
完全没有。