Question

In "using namespace" statement inside an anonymous namespace it was asked whether the following is legal

//file.cpp
//....
namespace
{
    using namespace std;
}

int a(){
 cout << "bla";
}

The answer was "It is". Further, using namespace directives are generally despised even if inserted in cpp files since the scope differences between header and implementation files are not rock solid since the introduction of unity builds (https://stackoverflow.com/a/6474774/484230).

My question: Does the anonymous namespace save me from such problems or can the using directive still propagate file borders? In https://stackoverflow.com/a/2577890/484230 a similar approach was proposed. Does it work for anonymous namespaces as well and is it really safe? Of course std is a bad example but e.g. using namespace boost::assign; would be quite handy in some cpp files.

Was it helpful?

Solution

There isn't any difference between putting it in an anonymous namespace and putting it outside one. Either one produces the same effect, which is bringing the entire std namespace into your file's top-level namespace. This isn't good and it should be avoided.

As for "propogating file borders", it wouldn't do that if you put it outside the anonymous namespace either. The only time it can infect other files is if it's in a file that's #included in other files, such as headers.

OTHER TIPS

My question: Does the anonymous namespace save me from such problems or can the using directive still propagate file borders ?

The only way the directive could propagate file borders is if some other file had a #include "file.cpp" preprocessor directive. That is perfectly legal, too, but whoo-ey, that stinks. Including a source file as opposed to a header is very much against standard practice.

Just because something is legal does not mean that it is good.

Pretty much the same goes for using the using to bring some other namespace into the current one. using namespace <name>; is general deemed to be bad form even in a source file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top