Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

c++ - 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

and

// m1.cpp

#include "foo.hpp"

int m1() {
    return bar();
}

//EOF

and

// 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

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 foos. So it violates the ODR, right?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This does violate the ODR. See 3.2/5 which is talking about extern inline functions (bar):

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...

In this case bar refers to two different versions of foo, thus violating the rule.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...