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