Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21881

What are the pitfalls of using shared pointers everywhere?

Our codebase uses many vectors. And some of these vectors share objects with each other, i.e. they contain std::shared_ptr to shared objects. The problem is: the codebase is still on active development stage, and it's often needed to rewrite some vector containing values to a vector containing shared pointers. And this is tedious. So I came up with an idea: simply make ALL vectors as vectors of shared pointers.

The question: is it OK? Which caveats should I be aware of? What can go wrong?

I've made some simple and possibly naive measurements and there was practically no difference in terms of performance between a vector of values and a vector of shared pointers when initializing and querying them.

If performance is not the problem, is there anything else I should be aware of?

Upvotes: 5

Views: 317

Answers (1)

gabry
gabry

Reputation: 1422

I think it's a bad idea, JAVA does this, and often this causes problems when you loose track that the object is shared and you "broke" it with some temporary change somewhere in your huge codebase.

There is almost no performance issues with std::vector if you use it with objects inside, except if the contained objects are really big or with complex constructors.

You should use pointers (shared or not) in a vector only when strictly needed, for instance:

  • if the contained object is polymorphic
  • if the contained object has some non trivially cloneable field (IE std::mutex)
  • if the contained object is really big (IE a video frame)

Upvotes: 4

Related Questions