gpt4 book ai didi

c++ - RValue 引用行为

转载 作者:行者123 更新时间:2023-11-30 02:45:03 26 4
gpt4 key购买 nike

我一直在努力理解移动构造函数场景背后发生的事情,但我的脑海中缺少了一些东西。

   struct A {
int s;
A() : s(10) {}
A(const A& o) : s(o.s) { std::cout << "copy contructor" << std::endl;}
A(A&& o) : s(std::move(o.s)) {std::cout <<"move constructor" << std::endl;}
};

struct B {
std::string s;
B() : s("max") {;}
B(const B& o) : s(o.s) {std::cout <<"copy contructor" << std::endl;}
B(B&& o) : s(std::move(o.s)) {std::cout <<"move contructor" << std::endl;}
};

int main() {

A a1;
std::cout << " Before move " << " " << a1.s << std::endl;
A a2 = std::move(a1);
std::cout << " After move" << " " << a1.s << std::endl;

B b1;
std::cout << " Before move" << " " << b1.s << std::endl;
B b2 = std::move(b1);
std::cout << " After move" << " "<< b1.s << std::endl;
return 0;
}

在一个对象上调用 std::move,应该清楚虽然对象在移动后仍然存在,但我们很乐意清空“。

The output is 
Before move 10
move constructor
After move 10

Before move max
move constructor
After move ""

我有两个问题:

1) 结构 B 的移动构造函数“窃取”了资源并使 b1.s 为空 ("")。这对我来说非常有意义,为什么 a1.s 没有发生这种情况。它看起来是一个拷贝而不是一个 Action 。

2) 如果我从结构 B 的移动构造函数中删除 std::move,

 B(B&& o) : s(o.s) {std::cout <<"move contructor" << std::endl;}

我想应该调用一个复制构造函数。现在输出是:

Before move max
move constructor
After move max

这对我来说有部分意义。我完全理解“最大移动后的资源”。现在它看起来是一个拷贝,但没有应该用复制构造函数调用打印出来的“复制构造函数”的痕迹。

我脑子里肯定缺少某些东西,有人可以解释为什么吗?谢谢

最佳答案

  1. 从原始类型移动与复制完全相同。只有在处理包含动态分配资源的对象时,移动才真正有意义。例如,std::string 将动态分配其字符串内容,这些内容正在从原始 std::string 移动到新字符串。

  2. 由于 std::move 这里仍然选择移动构造函数:

    B b2 = std::move(b1);

    表达式 std::move(b1) 是一个右值,因此将选择移动构造函数来构造 b2。改变移动构造函数的作用不会改变这一点。您改变的是移动构造函数的行为与复制构造函数相同(除了打印“使用移动构造函数”这一事实)。因为您已将 s(std::move(o.s)) 更改为 s(o.s),内部字符串将被复制过来。

    <

关于c++ - RValue 引用行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24839910/

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