我最近开始欣赏std::auto_ptr,现在我读到它将被弃用.我开始在两种情况下使用它:
例子:
// 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);
Run Code Online (Sandbox Code Playgroud)
尽管复制语义有问题,我觉得auto_ptr很有用.并且似乎没有上述示例的替代方案.
我应该继续使用它,然后切换到std::unique_ptr?还是要避免?
尽管存在缺陷,但它非常有用,我强烈建议继续使用它并切换到unique_ptr可用时.
::std::unique_ptr需要一个支持rvalue引用的编译器,它是C++ 0x草案标准的一部分,并且需要一段时间才能获得它的真正广泛支持.在rvalue引用可用之前,::std::auto_ptr您可以做到最好.
在代码中使用::std::auto_ptr和::std::unique_ptr使用可能会使某些人感到困惑.但是,::std::unique_ptr当您决定更改它时,您应该能够搜索和替换它.如果这样做,您可能会遇到编译器错误,但它们应该很容易修复.额定答案顶端这个问题有关更换::std::auto_ptr与::std::unique_tr有更多的细节.
| 归档时间: |
|
| 查看次数: |
2226 次 |
| 最近记录: |