When you instantiate objects and store them in a vector. What are the pros and cons between these three and in which instance should these be used?
Object:
std::vector<obj> collection;
collection.push_back(obj{});
Pointer to object:
std::vector<obj*> collection;
collection.push_back(new obj{});
Smart Pointer:
std::vector<std::unique_ptr<obj>> collection;
collection.push_back(std::unique_ptr<obj>(new obj{}));
If the object type supports copy and assignment, you should eschew pointers, and put the object in the vector (and everywhere else—you probably shouldn't have any pointers to such an object).
If the object type has identity, and doesn't support copy and
assignment (or only supports copy in order to implement
a clone function), then you'll need to keep pointers in the
vector. Whether smart pointers or raw pointers depends on what
the vector is being used for, and what the policy concerning the
lifetime of the object are. In my experience, most of the time,
vectors are used for navigation, in which case, you should use
raw pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With