【问题标题】:What is the reason that C++11 gives up auto_ptr? [duplicate]C++11放弃auto_ptr的原因是什么? [复制]
【发布时间】:2014-04-18 03:07:10
【问题描述】:

它放弃了auto_ptr,增加了unique_ptrshared_ptr。它们是否足以让 c++ 放弃auto_ptr?必须有有时auto_ptr 可能会导致不好的结果。谁能举个例子?

如果它不做坏事,C++11 会保留它而不是放弃。

【问题讨论】:

标签: c++ c++11 smart-pointers


【解决方案1】:

因为unique_ptrauto_ptr 的更好选择。

特别是,不可能将auto_ptr 存储在容器中。虽然您可以将unique_ptr 存储在容器中。

【讨论】:

  • 实际上从函数返回auto_ptr 没有问题。这是它唯一擅长的事情之一。
  • @MarkRansom 你是对的,已更正。这是有道理的,因为它转移了所有权,我一定对它的使用有不好的记忆。
【解决方案2】:

auto_ptr 是可复制构造的,用于移动所有权,例如,

    auto_ptr a;
    ....
    auto_ptr<int> b = a; // a loses its ownership here

这可能会导致混乱和错误。

unique_ptr 不可复制。它是移动可构造的,它移动所有权,例如,

    unique_ptr a;
    ....
    unique_ptr<int> b = a; // ERROR, wont compile

    unique_ptr<int> b = std::move(a); // OK, as programmer is explicitly moving ownership, no confusion

    unique_ptr<int> b = unique_ptr(p); // OK, ownership will move from temporary unique_ptr

shared_ptr 显然是为了共享所有权,所以:

    shared_ptr a;
    ...
    shared_ptr b = a; // both a and b have ownership, underlying pointer will only be freed when a and b both are out of scope

【讨论】:

    【解决方案3】:

    是的,auto_ptr 会导致不好的结果。

    如果您将一个auto_ptr 分配给另一个,第一个指针将完全丢失它的指针。这是一个令人惊讶的结果,会导致错误。

    auto_ptr<int> p1(new int(42));
    auto_ptr<int> p2 = p1;        // at this point p1 is a bad pointer
    

    unique_ptr 是一个更好的选择。

    【讨论】:

    • 同意。只需添加 unique_ptr 的解决方案就是使所有权转移显式和编译时检查。
    【解决方案4】:

    C++ 标准规定 STL 元素必须是“可复制构造的”和“可赋值的”。一个元素必须能够被分配或复制,并且这两个元素在逻辑上是独立的。 std::auto_ptr 不满足此要求。换句话说,STL 容器需要能够复制您存储在其中的项目,并且旨在期望原始和副本是等价的。自动指针对象具有完全不同的合同,复制会产生所有权转移。这意味着 auto_ptr 的容器会表现出奇怪的行为,具体取决于使用情况。

    unique_ptr 确实是 auto_ptr 的直接替代品,它结合了 std::auto_ptr 和 boost::scoped_ptr 的最佳特性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 2010-11-14
      • 2021-12-03
      • 2021-01-26
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多