简体   繁体   English

为什么shared_ptr具有移动构造函数

[英]Why does shared_ptr have a move constructor

In C++11 std::shared_ptr has a move constructor and move assignment operator. 在C ++ 11中, std::shared_ptr具有移动构造函数和移动赋值运算符。

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. (回想一下,多个线程可能正在复制拥有相同对象的自己的本地共享指针。)当您实际上想要所有权从一个对象转移到另一个对象时,不需要这样做,并且移动是上乘的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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