Trying to understand auto_ptr

I am trying to understand some details about how the auto_ptr class works. Suppose you have the following class (I found this on a website where a person explains the intricacies of an assignment operator).

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...
}

Now the implementation of the assignment operator.

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;
}

Next he says

Here, if the second new operation fails, the first new TBar will be deleted with auto_ptr destructor when we exit the function. But if both new successes succeed, the assignments will delete the fBar1 and fBar2 objects that were previously indicated, and will also zero out the strings bar1 and bar2 so that their destructors do not delete anything when they exit this function.

So my question is: why will bar1 and bar2 be reset to zero? What will cause this? You do not need to do something like

fBar = bar1.release();

Thanks for any help with this.

+4
1

auto_ptr , auto_ptr, . , . , , auto_ptr unique_ptr.

+4

Source: https://habr.com/ru/post/1527022/


All Articles