gpt4 book ai didi

c++17 结构化绑定(bind)和 move 语义

转载 作者:行者123 更新时间:2023-12-01 14:46:53 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is std::move(), and when should it be used?

(8 个回答)


1年前关闭。




我在读这个https://leanpub.com/cppmove (C++17 - The Complete Guide First Edition Nicolai M. Josuttisand)关于 c++17 结构化绑定(bind)和 move 语义,它给出了以下示例,其中从对象 ms move 完好无损:

MyStruct ms = { 42, "Jim" };   // struct has fields {int i, std::string s}
auto&& [v,n] = std::move(ms);

// author says: the structured bindings v and n refer to an anonymous
// entity being an rvalue reference to ms, while ms still holds its value:

std::cout << "ms.s: " << ms.s << '\n'; // prints "Jim"
我已经对此进行了测试,至少在实际运行中,这是真的。但这通常也是它应该如何工作的吗?按照作者之前对结构化绑定(bind)的解释的方式,以上内容应该等同于
MyStruct ms = { 42, "Jim" };
auto&& e = std::move(ms); // anonymous compiler constructed entity "e"
/*aliasname*/ v = e.i; // v and n act as if e was constructed as
// above and v/n assigned to e.i/e.s as here
/*aliasname*/ n = e.s;

std::cout << "ms.s: " << ms.s << '\n'; // prints "Jim"
问题:
所以如果这是一个有效的解释,不会 auto&& e = std::move(ms)原因 ms立即将其内容“move ”/“被盗”/“无效”?这样在“Jim”上面的两个(等效?)变体中都不会(保证)打印......?
澄清:我知道 std::move 不会 move 任何东西,而是从左值转换为右值,但我认为这意味着至少你不能指望 std::move 对象(此处为 ms )内容在后续使用中被保留/可用
标记为 What is std::move(), and when should it be used? 的骗子.然而,对于这个问题,有大约 300 人赞成,这个答案是: https://stackoverflow.com/a/27026280/11608725

The first thing to note is that std::move() doesn't actually moveanything. It changes an expression from being an lvalue (such as anamed variable) to being an xvalue. An xvalue tells the compiler:

You can plunder me, move anything I'm holding and use it elsewhere(since I'm going to be destroyed soon anyway)".

in other words, when you use std::move(x), you're allowing thecompiler to cannibalize x


所以我想困惑是允许的:-P
请为 c++17 的超傻瓜推荐一本好书并 move 语义——这本书的请求肯定是正确的;-)

最佳答案

would not auto&& e = std::move(ms) cause ms to immediately have its contents "moved"/"stolen"/"invalidated"?

std::move()只准备 ms要被 move ,它不会完全从它 move 。这就是为什么 e是对 MyStruct 的引用,而不是实际的 MyStruct目的。

关于c++17 结构化绑定(bind)和 move 语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63800876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com