Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using namespace in an anonymous namespace safe?

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.

like image 389
Martin Avatar asked Dec 20 '22 22:12

Martin


1 Answers

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.

like image 81
Seth Carnegie Avatar answered Dec 24 '22 01:12

Seth Carnegie