2

I believe there's a typo on this code snippet extracted from Stroustup's book, at its page 368 :

template <class X> class std::auto_ptr
{
    template <class Y> struct auto_ptr_ref { /* ... */ }; // helper class
    X * ptr;
    public :
    typedef X element_type;
    explicit auto_ptr(X* p =0) throw() { ptr = 0; }
    auto_ptr (auto_ptr& a) throw() { ptr = a.ptr; a.ptr = 0; } // note: not const auto_ptr&

    /* ... */
};

Shouldn't

explicit auto_ptr(X* p =0) throw() { ptr = 0; }

be

explicit auto_ptr(X* p =0) throw() { ptr = p; }

instead ?

skaffman
  • 398,947
  • 96
  • 818
  • 769
WaldB
  • 1,261
  • 7
  • 14

2 Answers2

3

The errata for the book makes some changes:

Chapter 14:

pg 367-368 A recent standards change modified the definition of auto_ptr. Please replace the last paragraph on page 367 and page 368 ...

Community
  • 1
  • 1
ta.speot.is
  • 26,914
  • 8
  • 68
  • 96
-3

I've looked in that book however I have a newer version, which has some extra pages.

Anyhow, that code looks correct because it's saying p = 0 and by saying ptr = p is the same thing with ptr = 0.

Bugster
  • 1,552
  • 8
  • 34
  • 56
  • 2
    No. the `p=0` in the argument list is not an assignment, it is a default value. – Mat Jan 22 '12 at 12:56
  • 1
    No it is not correct by saying ptr = 0 you will never assign the right value in case of constructor with argument call auto_ptr( new MyClass ); you will get 0 and memleak. – AlexTheo Jan 22 '12 at 12:58