Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique_ptr inheritance slicing and destructors

Tags:

c++

c++11

Consider the following fully functioning example:

#include <iostream>
#include <memory>

class A {
    public:
    A() {
        std::cout << "A() \n";
    }
    ~A() {
        std::cout << "~A \n";
    }

};
class B:public A {
    public:
    B() {       
        std::cout << "B() \n";
    }
    ~B() {
        std::cout << "~B() \n";
    }
};

int main() {
    std::cout << "Output: \n";
    {
        std::unique_ptr<A> TestB(new B());
    }

    return 0;
}

The output is:

Output: 
A() 
B() 
~A 

Is there any way for B's destructor to be called with inheritance like this? I was not aware that unique_ptrs also have slicing problem. Of course I can use std::unique_ptr<B> but I wanted to have a std::vector<std::unique_ptr<A>> and add inherited items.

Is there a way to have a list of std::unique_ptrs in combination with inheritance?

like image 275
Grapes Avatar asked May 15 '26 19:05

Grapes


1 Answers

When you say delete p; and the type of the most-derived object containing *p (colloquially "the dynamic type of *p") is not the same as the static type of *p, then the behaviour is undefined if the static type of *p is a class-type and does not have a virtual destructor.

To fix this, you need to say virtual ~A().

like image 134
Kerrek SB Avatar answered May 18 '26 18:05

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!