BlueTrin
BlueTrin

Reputation: 10073

Drawbacks of using boost::shared_ptr instead of boost::optional

Can someone explain if there is a drawback of using boost::shared_ptr to represent a value which could be null or undefined rather than using boost::optional, in terms of memory and performance ?

I have seen, where I work, many people using boost::shared_ptr to represent a value which can be null. Is there an overhead in terms of performance or memory usage ?

Upvotes: 3

Views: 1011

Answers (3)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275405

optional<T> is either an instance of T or not. shared_ptr is either an owning smart pointer to T or not.

Anything that is correct and efficient to pass by-value will be correct and efficient to pass by-optional compared to a shared pointer.

Allocations are reasonably expensive operations, and by-value is sometimes what you mean. In addition, optional clearly says what you mean, while a shared_ptr has many meanings.

Upvotes: 2

pmr
pmr

Reputation: 59811

Besides the obvious fact that a shared_ptr has to also manage a thread-safe reference count, there is also allocation. optional is stack-based, which means that it will not perform any dynamic allocation. A shared_ptr will have to perform at least one (often two: object and control block) dynamic allocations.

optional does none of the above.

Upvotes: 5

Tony Delroy
Tony Delroy

Reputation: 106116

shared_ptr has many additional responsibilities - like reference counting - so yes there's an overhead in memory and synchronisation. It would be silly to use shared_ptr for this reason alone.

Upvotes: 3

Related Questions