mardi 28 mars 2017

Parent class using default constructor; child class' destructor is unexpectedly called

I had a scenario in C++ that calls the child's destructor in a case where I didn't expect it. A minimal repro is below:

#include <cstdio>
#include <memory>

using namespace std;

class Parent {
public:
};

class Child : public Parent {
    public:
    ~Child() {
        printf("Got here\n");
    }
};

int 
main()
{
    shared_ptr<Parent> x(new Child);
}

Usually something like this is a bug. The developer intends that the child destructor is called, and the correct action would be to insert into the parent an empty virtual destructor. However, to my shock, both G++ 4.4.7 (yeah, I know it's old) and clang 3.4.2 compile this such that the child destructor is called.

Does this conform to the standard?

Aucun commentaire:

Enregistrer un commentaire