user695652
user695652

Reputation: 4275

Store Object or Pointer in a Vector

I asked a very similar question here but since it is such a fundamental issue I would like to state my (new) question more precicely.

Say I have a very complex class A and each instance of A is stored in multiple containers such as vectors, queues,...

Even in a static setting, meaning that the objects get added to the containers once and will not be deleted nor modified:
Should the containers now contain pointers to the objects or the objects itself?

Upvotes: 4

Views: 1963

Answers (3)

Michael Kristofik
Michael Kristofik

Reputation: 35188

If each instance of A is stored in multiple containers, then you must store (smart) pointers instead of the objects themselves. Otherwise each container would have its own unique copy. Modifying an instance in one container would not affect the others. Even if you're not modifying anything, storing full object copies doesn't say what you mean, i.e., that the instances across the containers are really the same.

Upvotes: 3

Andrew
Andrew

Reputation: 24846

If you need copies of objects - use objects. If you need to share objects or polymorphic behavior is desired - use containers of smart pointers. In case of using smart pointers you will both have automatic object destruction and polymorphic behavior.

For example:

std::vector<std::shared_ptr<MyObject>> v;
auto ptr = std::shared_ptr<MyObject>(new MyObject());
v.push_back(ptr);

If you need to store unique pointers (with no sharing):

std::vector<std::unique_ptr<MyObject>> v;
auto ptr = std::unique_ptr<MyObject>(new MyObject());
v.push_back(std::move(ptr));

Upvotes: 10

Thomas Matthews
Thomas Matthews

Reputation: 57678

If your objects are large, or have high copying costs or are complex to copy, then store smart pointers.

Upvotes: 2

Related Questions