简体   繁体   中英

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 ?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM