Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use an object in a vector and when to use a pointer to an object in a vector? [closed]

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{}));
like image 426
Jan Swart Avatar asked Nov 27 '25 04:11

Jan Swart


1 Answers

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.

like image 193
James Kanze Avatar answered Nov 29 '25 18:11

James Kanze