简体   繁体   English

在匿名命名空间中使用命名空间是否安全?

[英]Is using namespace in an anonymous namespace safe?

In "using namespace" statement inside an anonymous namespace it was asked whether the following is legal 匿名命名空间内的“using namespace”语句中 ,询问以下内容是否合法

//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 ). 此外,使用命名空间指令通常被鄙视,即使插入cpp文件中也是如此,因为自引入统一构建( 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? 我的问题:匿名命名空间是否使我免于此类问题,或者using指令是否仍能传播文件边框? In https://stackoverflow.com/a/2577890/484230 a similar approach was proposed. https://stackoverflow.com/a/2577890/484230中 ,提出了类似的方法。 Does it work for anonymous namespaces as well and is it really safe? 它是否也适用于匿名命名空间,它是否真的安全? Of course std is a bad example but eg using namespace boost::assign; 当然std是个坏例子,但是例如using namespace boost::assign; would be quite handy in some cpp files. 在一些cpp文件中会很方便。

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. 任何一个都产生相同的效果,这会将整个std命名空间带入文件的顶级命名空间。 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 #include d in other files, such as headers. 它唯一能够感染其他文件的是它是否在其他文件中包含#include d的文件中,例如标题。

My question: Does the anonymous namespace save me from such problems or can the using directive still propagate file borders ? 我的问题:匿名命名空间是否使我免于此类问题,或者using指令是否仍能传播文件边框?

The only way the directive could propagate file borders is if some other file had a #include "file.cpp" preprocessor directive. 指令传播文件边框的唯一方法是,如果某个其他文件具有#include "file.cpp"预处理程序指令。 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带来一些其他的命名空间到当前一个。 using namespace <name>; is general deemed to be bad form even in a source file. 即使在源文件中也被认为是不良形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM