看看这段代码:
输出结果为:
[1] CTOR(你好) [2] MOVE CTOR(将你好移动到 -> ) [3] DTOR of Hello(你好的析构函数) [4] MOVE CTOR(将你好 ### 移动到 -> ) [5] DTOR of Hello ###(你好 ### 的析构函数) [6] 现在两个相等:Hello ### ### [7] DTOR of Hello ### ###(你好 ### ### 的析构函数)
重要提示:为了测试目的,我已禁用了复制省略优化(使用 -fno-elide-constructors)。
函数 f() 构造了一个临时对象 [1] 并通过调用移动构造函数将资源从该临时对象移动到 myObject [2](此外,它还添加了 3 个 # 符号)。
最后,临时对象被销毁 [3]。
我现在期望myObject已经完全构建,并且它的name属性是"Hello ###"。
然而,移动构造函数再次被调用,所以我得到的是"Hello ### ###"。
class Foo
{
public:
string name;
Foo(string n) : name{n}
{
cout << "CTOR (" << name << ")" << endl;
}
Foo(Foo&& moved)
{
cout << "MOVE CTOR (moving " << moved.name << " into -> " << name << ")" << endl;
name = moved.name + " ###";
}
~Foo()
{
cout << "DTOR of " << name << endl;
}
};
Foo f()
{
return Foo("Hello");
}
int main()
{
Foo myObject = f();
cout << endl << endl;
cout << "NOW myObject IS EQUAL TO: " << myObject.name;
cout << endl << endl;
return 0;
}
输出结果为:
[1] CTOR(你好) [2] MOVE CTOR(将你好移动到 -> ) [3] DTOR of Hello(你好的析构函数) [4] MOVE CTOR(将你好 ### 移动到 -> ) [5] DTOR of Hello ###(你好 ### 的析构函数) [6] 现在两个相等:Hello ### ### [7] DTOR of Hello ### ###(你好 ### ### 的析构函数)
重要提示:为了测试目的,我已禁用了复制省略优化(使用 -fno-elide-constructors)。
函数 f() 构造了一个临时对象 [1] 并通过调用移动构造函数将资源从该临时对象移动到 myObject [2](此外,它还添加了 3 个 # 符号)。
最后,临时对象被销毁 [3]。
我现在期望myObject已经完全构建,并且它的name属性是"Hello ###"。
然而,移动构造函数再次被调用,所以我得到的是"Hello ### ###"。
return
语句的操作数被移动到返回值中。myObject
中。f()
еҲ°myObject
пјҢеӣ дёәеӨҚеҲ¶зңҒз•Ҙиў«зҰҒз”ЁгҖӮ - kennytmFoo(Foo&& ) = delete;
移动构造函数,程序仍然可以运行。) - undefined