我为什么要std :: move一个std :: shared

编程入门 行业动态 更新时间:2024-10-24 18:21:24
本文介绍了我为什么要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::move和std::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

本文发布于:2023-07-30 00:25:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1244951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我为   std   shared   move

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!