Is it safe to initialize an auto_ptr with a pointer to a derived class?

982 views Asked by At

Lets say I have a base class and a derived class:

class Base
{
    public:
        virtual ~Base() {}
        virtual void DoSomething() = 0;
};


class Child : public Base
{
    public:
        virtual void DoSomething()
        {
            // Do Something
        }
};

Is it safe to initialize an std::auto_ptr of the type of the base class with a pointer to an instance of the derived class? I.E. will an object created like this:

std::auto_ptr<Base> myObject(new Derived());

correctly call the destructor of the derived class instead of the base class without leaking memory?

3

There are 3 answers

2
Max Truxa On BEST ANSWER

Despite the fact that you shouldn't use std::auto_ptr anymore since the arrival of C++11;

Yes, this is safe as long as your base has a virtual destructor.

Without the virtual destructor on the base, (like Steve Jessop noted below) you would get undefined behavior, since the destructor of the deriving class would be unknown at the time of destruction, and hence not being executed. This is a dangerous problem since in many cases it stays unnoticed. E.g., if you would manage some kind of resource in a single-inheritance class, that should have been freed in the destructor, a leak would occur silently.

0
AudioBubble On

Perfectly safe.

Many references are available - try searching for "auto_ptr polymorphism".

e.g. http://www.devx.com/tips/Tip/14391

0
Dietmar Kühl On

As long as your class Base the std::auto_ptr<Base> is parameterized with has a virtual destructor you can initialize the std::auto_ptr<Base> with classes derived of Base and they will be properly destroyed if the std::auto_ptr<Base> destructor is instantiated when a definition of Base is visible.