在命名空间中使用声明的范围 [英] scope of using declaration within a namespace

查看:327
本文介绍了在命名空间中使用声明的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++头文件中使用命名空间中的using声明是安全的(正确的)如下:

Is it safe (and correct) in a C++ header file to use the using declaration within a namespace as follows:

#include <boost/numeric/ublas/vector.hpp>
namespace MyNamespace {
    using boost::numeric::ublas::vector;
    vector MyFunc(vector in);
}

是正确包含在MyNamespace块中的using boost :: numeric :: ublas :: vector,否则会污染包含此头的任何文件的命名空间?

I.e. is the "using boost::numeric::ublas::vector" properly contained within the MyNamespace block, or will this pollute the namespace of any file that includes this header?

推荐答案

不,它不安全 - 它不会污染另一个命名空间,但是由于其他原因是危险的:

No, it is not safe - it won't pollute another namespace, but it is dangerous for other reasons:

使用指令会将您指定的名称(目前可见)导入您使用它的命名空间。虽然您的使用只会对 MyNamespace 的用户可见,但outside code>使用声明。

A using directive will import anything that is currently visible by the name you specify into the namespace where you use it. While your using will only be visible to users of MyNamespace, other things from "outside" will be visible to your using declaration.

因为它将导入在声明点可见的内容,所以确切的行为将取决于在声明之前包含的头的顺序(可能有不同的事情从 boost :: numeric :: ublas :: vector )。因为你不能真正地控制哪些头包括在你的头之前(也不应该!头应该是自足的!),这可能导致非常奇怪的问题,其中你的函数将在一个编译单元中找到一个东西,而另一个在

So how is this dangerous when used in a header? Because it will import things that are visible at the point of the declaration, the exact behavior will depend on the order of headers you include before the declaration (There might be different things visible from boost::numeric::ublas::vector). Since you cannot really control which headers are included before your header (nor should you be! headers should be self-sufficient!), this can lead to very strange problems where your function will find one thing in one compilation unit, and another in the next.

根据经验,使用声明只能在所有都包含在.cpp文件中。在Sutter和Alexandrescu的书C ++编码标准(Item 59)中还有一个关于这个问题的项目。这里是一个引号:但这里是常见的陷阱:许多人认为使用在命名空间级别(...)发布的声明是安全的,他们不是,他们至少同样危险,在一个微妙和更阴险的方式。

As a rule of thumb, using declarations should only be used after all includes in a .cpp file. There's also an item on this exact issue in the book "C++ Coding Standards" by Sutter and Alexandrescu (Item 59). Here's a quote: "But here's the common trap: Many people think that using declarations issued at namespace level (...) are safe. They are not. They are at least as dangerous, and in a subtler and more insidious way."

即使不太可能你的名称使用在其他地方不存在这里),事情可能会变得丑陋:在标题中,所有声明应完全限定。

Even when it's unlikely that the name you are using doesn't exist anywhere else (as is probably the case here), things can get ugly: In a header, all declarations should be fully qualified. This is pain, but otherwise, strange things can happen.

编辑:请参阅迁移到命名空间,以深入描述示例和问题。

See Migrating to Namespaces for examples and the problem described in-depth.

这篇关于在命名空间中使用声明的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆