lundi 22 avril 2019

Ownership mistake about duplicated unique_ptr items in a vector

Considering the following code, how can I resolve the ownership problem I'm facing?

I need to handle this situation without making a copy of Item because I can't.

The Item and ItemContainer are part of an API which the user shouldn't concern about duplication, it means I need to silently add a pointer twice if user calls it twice for the same pointer.

I thought my deleter would resolve it, but it didn't.

I can't use an unordered_set for example, I should manage this situation as it is now.

ItemContainer.h:

typedef std::unique_ptr<Item, std::function<void(Item *)>> ItemDeleter;
std::vector<ItemDeleter> items_;

ItemContainer.cpp:

void ItemContainer::addItem(Item *item)
{
  ItemDeleter uniqPtrItem(item, [](Item *p) {
    if (p != nullptr) { 
      delete p; //it's crashing here, obviously
      p = nullptr;
    }
  });
  items_.push_back(std::move(uniqPtrTask));
}


main.cpp

int main() {
  Item *item = new Item();
  ItemContainer itemContainer;
  itemContainer.addItem(item);
  itemContainer.addItem(item);
}

Aucun commentaire:

Enregistrer un commentaire