Boost logo

Boost :

From: Guillaume Melquiond (guillaume.melquiond_at_[hidden])
Date: 2007-06-09 14:28:01

Le samedi 09 juin 2007 à 14:03 -0400, Gennadiy Rozental a écrit :

> Can anyone explain why unnamed namespace is a problem?

Inline functions referring to the content of an unnamed namespace will
break the one-definition rule, when their header is included several
times. Undefined behavior ensues.

The following example should make it clear:

// h.hpp
namespace { int a; }
inline int f() { return ++a; }

// a.cpp
#include "h.hpp"
void g() { f(); }

// b.cpp
#include "h.hpp"
void g();
int main() {
  return f();

Which value does this program return? Depending on the compiler and on
the level of optimization, it could be either 1 or 2.

If you use a named namespace instead, the behavior becomes deterministic
and the returned value is necessarily 2.

Best regards,


Boost list run by bdawes at, gregod at, cpdaniel at, john at