c++ - 我应该停止使用 auto_ptr 吗?

标签 c++

我最近开始欣赏 std::auto_ptr,现在我读到它将是 deprecated .我开始在两种情况下使用它:

  • 工厂的返回值
  • 传达所有权转让

例子:

// Exception safe and makes it clear that the caller has ownership.
std::auto_ptr<Component> ComponentFactory::Create() { ... }

// The receiving method/function takes ownership of the pointer. Zero ambiguity.
void setValue(std::auto_ptr<Value> inValue);

尽管存在有问题的复制语义,但我发现 auto_ptr 很有用。上面的例子似乎没有替代方案。

我应该继续使用它然后切换到 std::unique_ptr 吗?还是应该避免?

最佳答案

尽管存在缺陷,但它非常非常有用,我强烈建议您继续使用它并在它可用时切换到 unique_ptr

::std::unique_ptr 需要一个支持右值引用的编译器,右值引用是 C++0x 草案标准的一部分,并且需要一段时间才能真正广泛支持它。在右值引用可用之前,::std::auto_ptr 是你能做的最好的。

在您的代码中同时包含 ::std::auto_ptr::std::unique_ptr 可能会使某些人感到困惑。但是当您决定更改它时,您应该能够搜索和替换 ::std::unique_ptr。如果这样做,您可能会遇到编译器错误,但它们应该很容易修复。对 this question about replacing ::std::auto_ptr with ::std::unique_tr 的评价最高的答案有更多细节。

关于c++ - 我应该停止使用 auto_ptr 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3450167/

相关文章:

c++ - 使用 "template"编写 C 或 C++ 库

c++ - 如何在不暂停执行的情况下获取 X 窗口系统中的事件?

c++ - 同时学习 Visual C++ 2008 和 C++?有什么资源可以推荐吗?

python - tensorflow 模型 : How to identify input/output nodes name from a proto buff file?

c++ - WM_Paint 的 BeginPaint() 函数导致内存丢失

c++ - 为什么不能实例化带有 "non const"复制构造函数的对,而没有实例化一对是可能的?

c++ - 如何获取匹配数组

c++ - 使用数据库自​​动集成测试 C++ 应用程序

c++ - 创建动态二维数组的其他方法?

c++ - 检查A是否是B的子类?