试图理解auto_ptr

Trying to understand auto_ptr

本文关键字:ptr auto      更新时间:2023-10-16

我试图了解auto_ptr类如何工作的某些细节。假设你有以下类(我在一个网站上找到了这个,该人解释了赋值运算符的细节)。

class TFoo : public TSuperFoo {
    auto_ptr<TBar> fBar1;
    auto_ptr<TBar> fBar2;
public:
    TFoo& TFoo::operator=(const TFoo& that);
    // various other method definitions go here...
}

现在是赋值运算符的实现。

TFoo& TFoo::operator=(const TFoo& that)
{
    if (this != &that) {
        auto_ptr<TBar> bar1 = new TBar(*that.fBar1);
        auto_ptr<TBar> bar2 = new TBar(*that.fBar2);
        fBar1 = bar1;
        fBar2 = bar2;
    }
    return *this;
}

他接着说

在这里,如果第二个新操作失败,当我们退出函数时,第一个新的 TBar 将被 auto_ptr 的析构函数删除。但是,如果两个 new 都成功了,赋值将删除之前指向的对象 fBar1 和 fBar2,并且还将清零 bar1 和 bar2,以便在我们退出函数时它们的析构函数不会删除任何内容。

所以我的问题是为什么 bar1 和 bar2 会被归零?什么会触发它?你不必做这样的事情吗

fBar = bar1.release();

感谢您对此的任何帮助。

auto_ptr 的赋值运算符将对象的所有权转移给被分派者,从而有效地释放从中分配对象的auto_ptr。因此,赋值运算符的语义相当违反直觉。这可能是auto_ptr被弃用并应替换为unique_ptr的主要原因。