代码之家  ›  专栏  ›  技术社区  ›  StackedCrooked

我应该停止使用自动模式吗?

c++
  •  14
  • StackedCrooked  · 技术社区  · 14 年前

    我最近开始欣赏 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 ?还是应该避免?

    3 回复  |  直到 14 年前
        1
  •  5
  •   Community CDub    8 年前

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

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

    兼有 ::STD::AutoPPTR ::std::唯一指针 在您的代码中可能会混淆一些人。但是你应该能够搜索和替换 ::std::唯一指针 当你决定改变它的时候。如果这样做,您可能会得到编译器错误,但它们应该很容易修复。最佳答案 this question about replacing ::std::auto_ptr with ::std::unique_tr 有更多详细信息。

        2
  •  1
  •   jcoder    14 年前

    不推荐并不意味着它会消失,只是会有更好的选择。

    我建议在当前代码上继续使用它,但在新代码上使用新的替代方案(新程序或模块,而不是对当前代码的小改动)。一致性很重要

        3
  •  -1
  •   John Smith    14 年前

    我建议你去用助攻智能指针。