driftwood
driftwood

Reputation: 2109

Trying to understand auto_ptr

I'm trying to understand certain details about how auto_ptr class works. Suppose you have the following class (i found this on a web site where the person explains the finer points of the 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;
}

He goes on to say

Here, if the second new operation fails, the first new TBar will be deleted by auto_ptr's destructor when we exit the function. But if both new's succeed, the assignments will delete the objects fBar1 and fBar2 previously pointed to, and will also zero out bar1 and bar2 so that their destructors don't delete anything when we exit the function.

So my question is why will bar1 and bar2 be zeroed out? What would trigger that? Don't you have to do something like

fBar = bar1.release();

Thanks for any help on this.

Upvotes: 4

Views: 100

Answers (1)

Samuli Hyn&#246;nen
Samuli Hyn&#246;nen

Reputation: 670

The assignment operator of auto_ptr transfers ownership of the object to the assignee, effectively releasing the auto_ptr that the object is assigned from. Thus, the semantics of the assignment operator are fairly counterintuitive. That is probably a main reason why auto_ptr is deprecated and should be replaced by unique_ptr.

Upvotes: 3

Related Questions