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);
When creating smart pointers, it's best to go with their std::make_*
functions. vector::push_back
is overloaded for rvalue references, invoking it like this
Entities.push_back(std::make_shared<Entity>());
will hence construct an element in the vector by moving the std::shared_ptr
you passed in, hence no performance hit due to modifying the control block of the smart pointer here. Note also that vector::emplace_back
can't be used with std::make_shared
but instead only with a raw pointer, which should be avoided for the sake of exception handling and brevity (passing a raw pointer requires to manually create an Entity
instance on the heap).
You can use emplace_back to construct a new shared pointer:
Entity* entity = new Entity;
std::vector<std::shared_ptr<Entity>> Entities;
Entities.emplace_back(entity);
If you add address of an existing object, you will attempt to free the memory twice, because destructor of the shared pointer destroys the object:
Entity entity;
std::vector<std::shared_ptr<Entity>> Entities;
Entities.emplace_back(&entity);
// What happens when entity and shared pointer both go out of scope??
To avoid this, you either need to construct the object with new
or make a copy when you create the shared pointer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.