mercredi 24 août 2016

Multiple inheritance and unique_ptr destruction

I have the classic (possible problematic) multiple inheritance diamond scheme.

  • B inherits A
  • C inherits A
  • D inherits C and B

I want to have a std::vector that can contain either C or D objects so I make it as std::vector<C> which is D's dad and it works fine.

BUT when I use: std::vector<std::unique_ptr<C>> then I have segmentation fault upon the destruction of the vector.

** glibc detected *** ./a.out: free(): invalid pointer: 0x0000000009948018***

Why is there a difference? To me, even the first implementation is problematic.

Code

#include <string>
#include <vector>
#include <memory>

class A
{
public:
    A() = default;
};

class B : public virtual A
{
public:
    B() = default;
};

class C : public virtual A
{
public:
    C() = default;
};

class D : public B, public C
{
public:
    D() = default;
};


int main()
{
    { // this crashes
    std::vector<std::unique_ptr<C>> v;
    std::unique_ptr<D> s1(new D());
    v.push_back(std::move(s1));
    std::unique_ptr<C> s2(new C());
    v.push_back(std::move(s2));
    }

    { // this is fine
    std::vector<C> v;
    D s1;
    v.push_back(s1);
    C s2;
    v.push_back(s2);
    }

    return 0;
};

Aucun commentaire:

Enregistrer un commentaire