使用 boost::shared_ptr 以便以后替换它

Using boost::shared_ptr with a view to replacing it later

本文关键字:替换 ptr boost shared 使用      更新时间:2023-10-16

我正在研究需要共享指针的跨平台代码。由于我无法控制的原因,我们还不能使用 C++11。所以,我建议使用boost::shared_ptr。当我们采用 C++11 时(也许一年后),我们应该能够用 std 智能指针替换 boost 智能指针。我的问题是关于使用boost的最佳方法,以便以后更容易切换。模板别名不可用,因此以下内容已输出:

namespace my {
    template <typename T>
    using shared_ptr = boost::shared_ptr<T>;
}

另一种将shared_ptr包装在另一个结构中的技术会导致 API 丑陋且不可读,因为我将不得不使用它,因此my::shared_ptr<int>::type

 namespace my  {
     template<typename T>
     struct shared_ptr
     {
          typedef boost::shared_ptr<T> type;
     };
 }

我正在寻找替代方案。任何建议将不胜感激。

编辑:我考虑的另一个选择是:

namespace my {
     using boost::shared_ptr;
}

然后使用my::shared_ptr<int>.后来我会在namespace my boost改为std.但是,我无法决定每种方法的利弊以做出决定。

四个选项与 C++98 兼容,

1)使用impl::shared_pointer<T>。并从以下位置切换:

namespace impl = boost;namespace impl = std;

2)(更优雅但风险更大)是使用没有命名空间限定的shared_ptr,然后从

using boost::shared_ptr using std::shared_ptr .

3)(丑陋,但我想是首选的工业解决方案)一直使用宏。

#if DETECTC++11
#define SHARED_PTR std::shared_ptr
#else
#define SHARED_PTR boost::shared_ptr
#endif

4)结合上述3项。

匿名命名空间可以帮助将 using 语句保留在文件的本地,因此您可以控制每个源文件,例如:

namespace{
  using std::shared_ptr;
}

(我个人一直使用 2.)。

我们在项目中做了这样的事情:

#if compiler_doesnt_support_c++11
  #include <boost/shared_ptr.hpp>
  namespace std {
    using boost::shared_ptr;
  }
#elif compiler_has_c++11_in_tr1
  #include <memory>
  namespace std {
    using std::tr1::shared_ptr;
  }
#else
  #include <memory>
#endif

只需在代码中使用std::shared_ptr即可。

的,它在技术上是未定义的行为(因为您不允许像这样向::std命名空间添加名称),但它多年来一直没有任何问题。