1

My question is the following : is this following code correct :

class A {}; // no virtual destructor

class B : public A{
    std::unique_ptr<int> ptr{new int(5)};
};

// in main
std::unique_ptr<A> = new B;

It will probably have some compilation errors, but it is just to understand the concept. Will the pointer be correctly deleted (I mean ptr will be deleted?) or do we need virtual destructor to ensure that

Antoine Morrier
  • 3,593
  • 11
  • 28

1 Answers1

6

A smart pointer like std::unique_ptr only encapsulates the resource management. It doesn't change the semantics of pointers or polymorhpic use of types.

So you'll be deleting a B via a pointer to an A without a virtual d'tor, and that would still be undefined behavior. Just like with a raw pointer.

StoryTeller - Unslander Monica
  • 148,497
  • 21
  • 320
  • 399