匿名命名空间和一个定义规则 [英] anonymous namespaces and the one definition rule
问题描述
我违反了单一定义规则与以下程序?
Am I violating the One Definition Rule with the following program?
// foo.hpp
#ifndef FOO_HPP_
#define FOO_HPP_
namespace {
inline int foo() {
return 1;
}
}
inline int bar() {
return foo();
}
#endif
//EOF
p>
and
// m1.cpp
#include "foo.hpp"
int m1() {
return bar();
}
//EOF
和
// m2.cpp
#include "foo.hpp"
int m2() {
return bar();
}
//EOF
>
and finally
// main.cpp
#include <iostream>
int m1();
int m2();
int main(int, const char* [])
{
int i = m1();
int j = m2();
std::cout << (i+j) << std::endl;
return 0;
}
// EOF
foo()
是在匿名命名空间中定义的,所以我期望每个翻译单元 m1.cpp
和 m2.cpp
会得到自己的版本,所以没有违反ODR。另一方面, bar()
只是一个普通的内联函数,恰巧调用了两个不同的 foo
。
In the above, note that foo()
is defined in an anonymous namespace, so I expect that each translation unit m1.cpp
and m2.cpp
will get its own version, so there is no violation of the ODR. On the other hand, bar()
is just a plain old inline function which happens to call 2 different foo
s. So it violates the ODR, right?
更新:
以前我在的定义中有宏, foo
更改了它返回的值,并且每个 m1
和 m2
之前包含 foo.hpp
。 (和前面的例子一样, g ++
会产生一个输出(i + j)
)但实际上这个程序违反了ODR,即使 foo()
的主体是相同的。
Update:
Previously I had macros in the definition of foo
that changed the value it returned and each of m1
and m2
defined the macro differently before including foo.hpp
. (And with that previous example, g++
would produce a binary that output (i+j)
with a value other than what you would expect.) But in fact this program violates the ODR even if the body of foo()
is identical.
推荐答案
这违反了ODR。参见3.2 / 5,其中涉及外部内联函数( bar
):
This does violate the ODR. See 3.2/5 which is talking about extern inline functions (bar
):
在D的每个定义中,根据
3.4查找的相应名称应指在D的定义内定义的实体,或者应当指代相同的实体...
in each definition of D, corresponding names, looked up according to 3.4, shall refer to an entity defined within the definition of D, or shall refer to the same entity...
在这种情况下, bar
是指两个不同版本的 foo
,因此违反了规则。
In this case bar
refers to two different versions of foo
, thus violating the rule.
这篇关于匿名命名空间和一个定义规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!