我为什么要std :: move一个std :: shared_ptr? [英] Why would I std::move an std::shared_ptr?

查看:1372
本文介绍了我为什么要std :: move一个std :: shared_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在浏览 Clang源代码,并且找到了以下代码段:

I have been looking through the Clang source code and I found this snippet:

void CompilerInstance::setInvocation(
    std::shared_ptr<CompilerInvocation> Value) {
  Invocation = std::move(Value);
}

我为什么要std::movestd::shared_ptr?

在共享资源上转移所有权是否有意义?

Is there any point transferring ownership on a shared resource?

我为什么不这样做呢?

void CompilerInstance::setInvocation(
    std::shared_ptr<CompilerInvocation> Value) {
  Invocation = Value;
}

推荐答案

我认为其他答案未充分强调的一件事是 speed 的意义.

I think that the one thing the other answers did not emphasize enough is the point of speed.

std::shared_ptr参考计数是 atomic .增加或减少参考计数要求 atomic 递增或递减.这比非原子增量/减量慢一百倍,更不用说如果我们增加或减少相同的计数器,我们就会得到确切的数字,浪费一吨的时间和资源.

std::shared_ptr reference count is atomic. increasing or decreasing the reference count requires atomic increment or decrement. This is hundred times slower than non-atomic increment/decrement, not to mention that if we increment and decrement the same counter we wind up with the exact number, wasting a ton of time and resources in the process.

通过移动shared_ptr而不是复制它,我们可以窃取" atomic 引用计数,并使另一个shared_ptr无效. 窃取"引用计数不是 atomic ,它比复制shared_ptr快一百倍(并导致 atomic 引用增量或递减).

By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr. "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).

请注意,此技术仅用于优化.复制它(按照您的建议),在功能上也一样.

Do note that this technique is used purely for optimization. copying it (as you suggested) is just as fine functionality-wise.

这篇关于我为什么要std :: move一个std :: shared_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆