如您所述,std::auto_ptr 在 C++11 中已被弃用
(Reference)。
移至 c++11 std::unique_ptr 是正确的方法,正如 Herb Sutter 在
GotW89:
- 与 auto_ptr 有什么关系?
auto_ptr 最慷慨地描述为在 C++ 具有移动语义之前创建 unique_ptr 的勇敢尝试。 auto_ptr 现已弃用,不应在新代码中使用。
如果您在现有代码库中有 auto_ptr,当您有机会尝试将 auto_ptr 全局搜索并替换为 unique_ptr 时;绝大多数用途都是一样的,它可能会暴露(作为编译时错误)或修复(默默地)一两个你不知道的错误。
另请注意,C++17 将删除 std::auto_ptr。
我认为可能有不同的方法可以解决您的问题,“正确”的方法还取决于您的实际代码是如何编写的。
几个选项是:
选项 1
使用 boost::unique_ptr
选项 2
根据 __cplusplus 有条件地使用 auto_ptr 或 unique_ptr。
类 Myclass {
#if __cplusplus
std::auto_ptr m_ptr;
#其他
std::unique_ptr m_ptr;
#endif
...
这将分散在您引用 auto_ptr 的每个地方,我不太喜欢它。
如果您对 std::auto_ptr 的所有引用都已经被 typedef 了(只是有条件地更改 typedef),那么可能看起来不那么尴尬。
选项 3
有条件地使用 using 和 aliasing 来“定义”auto_ptr(并在没有 std:: 命名空间的情况下引用它)。
#if __cplusplus
使用 std::auto_ptr;
#其他
模板
使用 auto_ptr = std::unique_ptr;
#endif
缺点:你一直在使用“auto_ptr”,但在 c++11 中它意味着 std::unique_ptr。
真是迷惑……
选项 3.1
可能比选项 2 略好:
使用别名进行反向,并首选 unique_ptr 名称。
选项 4
将 std:: 智能指针(条件为 auto_ptr 或 unique_ptr)包装在您自己定义的模板智能指针类中。
这可能很麻烦,需要使用新类搜索和替换所有 auto_ptr 引用。
其他脏选项
其他选项涉及 std:: 命名空间内的定义,我认为这是标准禁止的,
或者使用预处理器#define to ...ehm...“rename” unique_ptr to auto_ptr 仅适用于旧的 C++03 编译器。