简体   繁体   中英

Why does shared_ptr have a move constructor

In C++11 std::shared_ptr has a move constructor and move assignment operator.

Is there a reason why this is needed, ie would any programs using it behave differently if there were only the copy constructor and assignment operators?

It seems that the only effect of it is that the extra increment and later decrement of the reference counter is avoided.

Copying a shared pointer is very expensive, since the internal reference counts need to be modified atomically and with the correct memory ordering, which may incur bus locks and fences. (Recall that multiple threads may have be copying their own, local shared pointers that own the same object.) When you actually want to transfer ownership away from one and into another object, none of this is needed, and moving is superior.

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