0

In my game engine, there is a pointer stored in the entity manager class to the currently selected entity. In the entity manager, there is also a vector of unique pointers to all the entities in the scene. I want to set up a duplication feature, where the selected entity is pushed back into the vector with the id modified, but otherwise the same.

I tried:

if (selectedEntity) {
    Entity e = *selectedEntity;

    e.id = currentID;
    currentID++;

    std::unique_ptr<Entity> uPtr{ &e }; 

    entities.emplace_back(std::move(uPtr));
}

But it causes errors that say I'm trying to reference a deleted function. My guess is it's to do with the line std::unique_ptr<Entity> uPtr{ &e };, but I'm not sure how to fix it. How can I handle this in a way that is efficient, and that will work every time?

veridis_quo_t
  • 342
  • 3
  • 14
  • 1
    [Couldn't reproduce](https://wandbox.org/permlink/CA0GEGURs96sqMIV). Please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). By the way, why are you storing a pointer to local object? – MikeCAT Jul 19 '20 at 10:12
  • I assume you're using `unique_ptr` to store classes derived from `Entity`? Then `Entity e = *selectedEntity;` causes [object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing). And `unique_ptr uPtr{ &e };` is also wrong, because the pointer you pass doesn't point to the heap. – HolyBlackCat Jul 19 '20 at 10:14
  • You need to add something like `virtual unique_ptr clone() const {...}` to `Entity`, and override it for each derived class to do the right thing. – HolyBlackCat Jul 19 '20 at 10:15
  • Maybe I'm just being obtuse, but why would you want to **duplicate** a **unique** pointer? Wouldn't really be *unique* then, would it. – Adrian Mole Jul 19 '20 at 10:16
  • @AdrianMole It seems OP wants to allocate a new object, and create a new `unique_ptr` to point to it. – HolyBlackCat Jul 19 '20 at 10:17

1 Answers1

0

You can make a unique_ptr using the copy constructor:

std::make_unique<Entity>(e)
Daniel
  • 30,896
  • 18
  • 85
  • 139
  • This will only work if OP doesn't store classes derived from `Entity` in the `unique_ptr`s. In which case they might as well use `vector`, without `unique_ptr`. – HolyBlackCat Jul 19 '20 at 10:19
  • @HolyBlackCat: OP didn’t say anything about polymorphism. – Daniel Jul 19 '20 at 12:36