Is it legal to place using tr1::shared_ptr in namespace std in header?

久未见 提交于 2019-12-04 12:53:23

问题


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;
}

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.


回答1:


Technically, the Standard says that you enter the realm of Undefined Behavior if you do this:

17.6.4.2.1 Namespace std [namespace.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.

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.

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.



来源:https://stackoverflow.com/questions/16366674/is-it-legal-to-place-using-tr1shared-ptr-in-namespace-std-in-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!