Using raw pointers, I can create a vector of pointers and push_back addresses like so:
Entity objEntity;
std::vector<Entity*> Entities;
Entities.push_back(&objEntity);
If I instead use a vector of shared pointers:
std::vector<std::shared_ptr<Entity>> Entities;
... how do I push_back the addresses?
From what I understand, std::shared_ptr::reset is used in order to assign the address of an existing object to a smart pointer. Do I need to first create a temporary pointer, call reset, and then push_back?
std::shared_ptr<Entity> temp;
temp.reset(&objEntity);
Entities.push_back(temp);
You can use emplace_back
to construct a new shared pointer from an existing pointer:
Entity* entity = new Entity;
std::vector<std::shared_ptr<Entity>> Entities;
Entities.emplace_back(entity);
Alternatively you can use push_back
to construct the object with make_shared
.
Entities.push_back(std::make_shared<Entity>());
There is no way to safely add existing objects (that were not created as pointers to begin with). You can add an existing pointer, or make a copy when you create the shared pointer.
If you add the address of an existing object, you will attempt to free the memory twice, because the destructor of the shared pointer destroys the object:
Entity entity;
std::vector<std::shared_ptr<Entity>> Entities;
Entities.emplace_back(&entity); // incorrect usage
// What happens when entity and shared pointer both go out of scope??