Menu

unique_ptr and base classes without a virtual destructor

Fraser
2019-07-15
2019-07-17
  • Fraser

    Fraser - 2019-07-15

    Here is a quote from cppreference.com: "If T is a derived class of some base B, then std::unique_ptr<t> is implicitly convertible to std::unique_ptr. The default deleter of the resulting std::unique_ptr will use operator delete for B, leading to undefined behavior unless the destructor of B is virtual."</t>

    I suspect that cppcheck does not catch this undefined behaviour and it is not something a compiler warns about either.

     
  • Daniel Marjamäki

    I suspect so too. Could you create a minimal example code? Do you have a Trac account? Then please feel free to create a ticket.

     
  • Fraser

    Fraser - 2019-07-17

    I will put this on trac as well.

    class Base {
    public:
    virtual ~Base()= 0;
    Base() {
    std::cout << "Base constructor" << '\n';
    }
    };

    Base::~Base() {
    std::cout << "Base destructor" << '\n';
    }

    class Base2 {
    public:
    ~Base2();
    Base2() {
    std::cout << "Base2 constructor" << '\n';
    }
    };

    Base2::~Base2() {
    std::cout << "Base2 destructor" << '\n';
    }

    class Leaker :
    public Base2 {
    public:
    ~Leaker();
    Leaker() {
    std::cout << "Leaker constructor" << '\n';
    }
    };

    Leaker::~Leaker() {
    std::cout << "Leaker destructor" << '\n';
    }

    class NonLeaker :
    public Base {
    public:
    ~NonLeaker();
    NonLeaker() {
    std::cout << "NonLeaker constructor" << '\n';
    }
    };

    NonLeaker::~NonLeaker() {
    std::cout << "NonLeaker destructor" << '\n';
    }

    std::unique_ptr<base2> CreateLeaker() {
    return std::make_unique<leaker>();
    }</leaker></base2>

    std::unique_ptr<base> CreateNonLeaker() {
    return std::make_unique<nonleaker>();
    }</nonleaker>

    int _tmain(int argc, _TCHAR* argv[])
    {
    {
    auto nl= CreateNonLeaker();
    }
    {
    auto l= CreateLeaker();
    }
    return 0;
    }

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.