4

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.

driftwood
  • 1,583
  • 3
  • 15
  • 25
  • 1
    The only thing to understand about `auto_ptr` is it's broken and should not be used. – Captain Obvlious Feb 14 '14 at 21:16
  • @CaptainObvlious it is perfectly fine for some situations. If you have C++11 then there is no reason to use it. But in C++03 there sometimes is no good alternative. Anyway, the question is a good one and applies to `unique_ptr` too. – juanchopanza Feb 14 '14 at 21:18
  • You might want to learn about the [Copy-Swap Idiom](http://stackoverflow.com/q/3279543/10077). – Fred Larson Feb 14 '14 at 21:21

1 Answers1

3

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.

Samuli Hynönen
  • 652
  • 1
  • 8
  • 22
  • ok thanks. but I still want to understand...I guess a more fundamental C++ question that's bothering me. bar1 is the one being assigned. so it wouldn't know to zero itself out, right? therefore I'm guessing that since fBar1 is also an auto_ptr it must be zeroing bar1 out in fBar1's assignment operator, does that sound right or not?? Thanks for all the answers. – driftwood Feb 14 '14 at 22:55
  • 1
    @user2722568: that's right. The assignment operator invoked on the destination operand `fBar1` modifies its source operand `bar1`. – Sean Middleditch Feb 14 '14 at 23:37
  • ok great thanks. the original author's (of Tbar/TFoo class)language was confusing me. – driftwood Feb 14 '14 at 23:41