在标题中的名称空间std中使用tr1 :: shared_ptr放置是否合法? [英] Is it legal to place using tr1::shared_ptr in namespace std in header?
问题描述
使用std::tr1::shared_ptr
作为std::shared_ptr
并将using
指令放置在相应的 header 中是否合法且良好的编程风格?像这样:
Is it legal and good programming style to use std::tr1::shared_ptr
as std::shared_ptr
placing using
directive in corresponding header? Like this:
namespace std
{
using tr1::shared_ptr;
}
我知道污染整个名称空间很不好,但是这种情况呢?有隐藏的陷阱吗?目标编译器是VS2008,但还需要与更高版本兼容.
I know that it's bad to pollute entire namespace but what about this case? Are there any hidden gotchas? Target compiler is VS2008 but compatibility with later versions is also desired.
推荐答案
从技术上讲,标准规定,如果您执行以下操作,则您将进入未定义行为"领域:
Technically, the Standard says that you enter the realm of Undefined Behavior if you do this:
17.6.4.2.1命名空间标准[namespace.std]
1如果C ++程序添加了声明或 定义到命名空间std或命名空间std中的命名空间 除非另有说明.
1 The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified.
但是在实践中,您很可能会摆脱它.哎呀,甚至斯科特·迈耶斯(Scott Meyers)在《有效C ++第三版》中也提出了一个类似的未定义名称空间别名的技巧. (第54页,第268页)将Boost功能用作缺少tr1
功能的权宜之计.
But in practice, you are likely to get away with it. Heck, even Scott Meyers proposed a similarly undefined namespace alias trick in Effective C++ 3rd Ed. (Item 54, p.268) to use Boost functionality as a stopgap for missing tr1
functionality.
namespace std { using namespace tr1 = ::boost; }
您的使用声明也是未定义的行为,但请继续并直接跳入.
Your using declaration is also undefined behavior, but go ahead and jump right in.
注意:在您的编译器版本和警告周围添加一个大的警告,#define
和#pragma
进行注释,并且一旦升级到实际具有std::shared_ptr
的编译器/库,请确保重新访问该文件.标头并删除代码.
NOTE: comment it with a big fat warning, #define
and #pragma
around your compiler version and warnings, and as soon as you upgrade to a compiler/library that actually has std::shared_ptr
, make sure to revisit that header and remove the code.
这篇关于在标题中的名称空间std中使用tr1 :: shared_ptr放置是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!