3

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?

B Faley
  • 17,120
  • 43
  • 133
  • 223
TwentyMiles
  • 4,063
  • 3
  • 30
  • 37
  • That question doesn't depend on auto_ptr, does it? It pertains to all pointers. If you couldn't do that you couldn't have polymorphism in C++ which would be sad. – Peter - Reinstate Monica Mar 12 '14 at 23:31
  • @PeterSchneider This question is specific to auto_ptr. Mainly I wanted to make sure that its [implementation didn't slice the object passed in](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c), but I also wanted to learn the gotchas like the one about virtual destructors. – TwentyMiles Mar 13 '14 at 15:10

3 Answers3

6

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.

Community
  • 1
  • 1
Max Truxa
  • 3,308
  • 25
  • 38
  • 1
    Be aware that it is undefined behavior to delete an object using a base class pointer where the base doesn't have a virtual destructor. One possible result is a memory leak, but anything is permitted so it could be worse. For example where there is multiple inheritance it's likely to crash or corrupt the data structures used by the memory allocator. – Steve Jessop Dec 11 '13 at 01:27
  • Thanks, added that to my answer. – Max Truxa Dec 11 '13 at 12:39
0

Perfectly safe.

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

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

0

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.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380