Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top