dimanche 30 avril 2017

std::remove_if polymorphic std::unique_ptr from std::vector

I have a hierarchy of three classes where Derived derives from Selectable and Drawable. Then I have a vector of unique_ptr<Drawable> which I fill with Derived objects.

I am certain that the vector will be filled only by objects which derive from both bases simultaneously.

The problem comes when I try to remove a certain element from the vector by using a pointer to Selected.

#include <vector>
#include <memory>
#include <algorithm>

struct Selectable {
    virtual ~Selectable() = 0;
};
Selectable::~Selectable() = default;

struct Drawable {
    virtual ~Drawable() = 0;
};
Drawable::~Drawable() = default;

struct Derived : Selectable, Drawable {};

int main()
{
    std::vector<std::unique_ptr<Drawable>> vec;
    for (int i = 0; i < 5; ++i) {
        vec.push_back(std::make_unique<Derived>());
    }
    Selectable* selected = dynamic_cast<Selectable*>(vec[2].get());

    vec.erase(std::remove_if(vec.begin(), vec.end(), 
        [selected](auto&& ptr) { 
            return ptr.get() == dynamic_cast<Drawable*>(selected); 
    }), vec.end());
}

Obviously if I make selected to be a pointer to Drawable, everything is fine, but that is not my intention.

I am getting a run-time error which causes the program to crash. Why is this happening and how would I fix it?

Aucun commentaire:

Enregistrer un commentaire