Steven Lu
Steven Lu

Reputation: 43437

What are the performance considerations of using a std::vector<boost::shared_ptr<Base_Class>> or boost::ptr_vector<Base>?

The benefits to having a vector of reference-counted smart pointers are many. I no longer have to worry about cleaning up the memory, and I can even store pointers to derived classes in the container and they will be handled just fine also.

This is all really wonderful, but it makes me wonder about the implications. If my container is able to correctly clean up pointers to derived classes that I may have inserted into it, that means that a RTTI of some sort must occur. Would that cost be incurred even if I never place derived class pointers into the container, ever?

Upvotes: 1

Views: 402

Answers (2)

user1084944
user1084944

Reputation:

My usual advice for most questions about performance is:

  • The performance considerations probably do not outweigh other concerns like making simple, straightforward code
  • If you still think they might be important (or you're just curious), one cannot reliably think your way the answer: you really need to measure it.

As the other answer said, there is no RTTI going on here; when the reference count drops to zero, shared_ptr simply invokes delete destroying your object in the normal fashion. (or it does something effectively equivalent)

Any performance implications involved should pretty much be limited simply to the differences between T* and shared_ptr<T>. (although I'm not familiar with ptr_vector....)

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477070

There is no RTTI, just straight-forward polymorphism. If your class hierarchy is already polymorphic (i.e. has virtual destructors, etc.), then there's absolutely no additional cost coming from the polymorphism.

What you should worry about is the cost of the shared pointer. If possible, see if a unique_ptr<Base> is actually enough. The atomic reference count update of the shared pointer is possibly a non-negligible cost.

Upvotes: 1

Related Questions