0

This example was taken from Stroustup's book, third edition, Section 14.4.2 :

void f (Point p1, Point p2, auto_ptr<Circle> pc, Shape* pb)
{
    auto_ptr<Shape> p (new Rectangle(p1 ,p2));
    auto_ptr<Shape> pbox(pb);
    p->rotate(45);
    / / ...
    if (in_a_mess ) throw Mess();
    / / ...
}

"Here the Rectangle, the Shape pointed to by pb, and the Circle pointed to by pc are deleted whether or not an exception is thrown."

WaldB
  • 1,261
  • 7
  • 14

1 Answers1

1

It's destroyed because that's what auto_ptr does. It destroys the pointed-to object in its destructor, and the destructor is called when the auto_ptr leaves scope, whether or not an exception is thrown. That's just how C++ works.

Internally, auto_ptr is essentially (relevant bits only):

template <typename T>
struct auto_ptr
{
    auto_ptr(T* ptr) : m_ptr(ptr) {}
    ~auto_ptr() { delete m_ptr; }
private:
    T* m_ptr;
};
Peter Alexander
  • 53,344
  • 14
  • 119
  • 168