在下面的代码中,我定义了一个简单的 log
函数。在 main
中,我尝试不调用它;我调用 std::log
。尽管如此,还是调用了我自己的log
;我看到“日志!”在屏幕上。有谁知道为什么?我使用 G++ 4.7 和 clang++ 3.2。
#include <iostream>
#include <cmath>
double log(const double x) { std::cout << "log!\n"; return x; }
int main(int argc, char *argv[])
{
std::log(3.14);
return 0;
}
最佳答案
C++ 标准 17.6.1.2 第 4 段(强调我的):
Except as noted in Clauses 18 through 30 and Annex D, the contents of each header
cname
shall be the same as that of the corresponding headername.h
, as specified in the C Standard library (1.2) or the C Unicode TR, as appropriate, as if by inclusion. In the C++ standard library, however, the declarations (except for names which are defined as macros in C) are within namespace scope (3.3.6) of the namespacestd
. It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespacestd
by explicit using-declarations (7.3.3).
g++ 以后一种方式实现,因此一些相同的头文件可以被 C 和 C++ 重用。所以g++被允许在全局命名空间中声明和定义double log(double)
。
第 17.6.4.3.3 节第 3 和第 4 段:
Each name from the Standard C library declared with external linkage is reserved to the implementation for use as a name with
extern "C"
linkage, both in namespacestd
and in the global namespace.Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both
extern "C"
andextern "C++"
linkage, or as a name of namespace scope in the global namespace.
在第 17.6.4.3 节第 2 段的顶部:
If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined.
另一方面,您可以不以任何方式声明或定义::log
。
可惜 g++ 工具链没有给你任何错误信息。
关于c++ - 为什么我的日志在 std 命名空间中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43500813/