我最近开始欣赏 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/