Search code examples
c++destructorauto-ptr

Why the Shape pointed by pb is destroyed when an exception is thrown in the example below?


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


Solution

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