我是唯一一个觉得 std::move 有点难以理解的人吗?
所以我一直在 SO 和其他地方阅读有关 std::move 、 std::forward 、右值、左值广告等的内容。但我发现我抓不住。尽管我有时会进行修复,但我认为我了解 C++ 中关于指针、引用等的基本内容。是我的问题还是这些东西太重了?
So I have been reading about std::move
, std::forward
, rvalues, lvalues ad so on in SO and other places. But I find that I can't grasp it. Even though I sometimes get into fixes, I think I understand basic stuff about pointers, references, etc which were in C++ before all this. Is it me or are these stuff getting too heavy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您还没有阅读原始提案,我建议您阅读:
它非常清楚地列出了可以使用右值引用和移动语义解决的问题,以及如何使用右值引用和移动语义来解决这些问题。
标准委员会的文件通常晦涩难懂,但这篇文章很容易理解,非常值得一读。最终 C++0x 标准中指定的右值引用和移动语义(无论何时发生)可能与本文中提出的不同,但概念仍然相同。
I would recommend reading the original proposal if you haven't already:
It lays out very clearly the problems that can be solved with rvalue references and move semantics and how rvalue references and move semantics can be used to solve those problems.
Standards committee papers are often dense and difficult to understand, but this one is quite accessible and very much worth reading. The rvalue references and move semantics as specified in the final C++0x standard (whenever that happens) may be different from what is proposed in this paper, but the concepts are still the same.
你的问题很笼统。也许我可以帮助您开始:
std:move()
和std::forward()
Matrix z = a + b + c + d;
的临时数(使用Matrix a,b,c,d;
)Matrix
上自行实现operator+
。如果您想查看
std::move()
的简单用法:帮助编译器避免引入返回值的副本:Image
这样的容器类 - - 复制成本高昂。发明一个像这样工作的工厂函数:
你能数一下临时变量的数量吗?请注意,
退货
将需要额外的一份和副本! (该示例的设计使得返回值优化(“RVO”)不应该成为可能)ii
中的图像将被丢弃。编译器可以使用 then 作为返回值吗? (不,它不能。如果我们只有一个Image
,RVO 就可以工作)。return
中的move
,您可以告诉编译器您不再需要ii
并且它可以将其用于返回。因此,我可以使用 move-c'tor 而不是 copy-c'tor 进行退货,从而节省昂贵的副本。Your question is very general. Maybe I can get you started:
std:move()
andstd::forward()
at the beginningMatrix z = a + b + c + d;
(withMatrix a,b,c,d;
)operator+
onMatrix
with overloaded RValue References.If you want to see a simple use of
std::move()
: Help the compiler to avoid introducing a copy for a return value:Image
-- costly to copy.invent a factory function that works like this:
Can you count the numbers of temporaries? Note that the
return
will need an additional one and copy! (The example is designed so that return-value-optimization ("RVO") should not be possible)ii
will be thrown away shorty after the function returned. Could the compiler use then for the return value? (No it could not. RVO would work if we had only oneImage
).move
in thereturn
you can tell the compiler, that you do not needii
further and that it can use it for the return. And thus spare a costly copy my using the move-c'tor instead of the copy-c'tor for the return.