使用 boost::shared_ptr 以便以后替换它
Using boost::shared_ptr with a view to replacing it later
我正在研究需要共享指针的跨平台代码。由于我无法控制的原因,我们还不能使用 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
命名空间添加名称),但它多年来一直没有任何问题。
- 模板参数替换失败,并且未完成隐式转换
- 如何用转义符替换字符串中的所有特殊字符
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在一个读写器队列中,我可以用volatile替换原子吗
- 用符号版本替换对函数的所有调用
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 替换基于地图的所有引用
- 按平均值替换数组中的元素
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 初始化 std::vector 替换为单大括号而不是双大括号
- 删除/替换C++字符串中的多字符 (ÿû)
- 将 malloc 替换为数组
- 如何替换此示例代码片段中已弃用的handler_type_t或 boost::asio::handler_type?
- 如何在C++中用'\'替换''来处理转义序列?
- 替换密码:哪一个?
- 为共享 ptr 向量实现复制 c'tor?