c++primer(第5版)中的一段程序:(P561)
class Quote {
public:
virtual Quote* clone() && {
return new Quote(std::move(*this));
}
};
书上解释说该右值引用函数将自身移动到新数据中。
疑问:
变量应该保存在栈内存中,而new动态分配的内存应当保存在堆内存中。这样的话,使用std::move()右值引用来将变量“移动”到动态内存中应当没有意义。
#include <memory>
#include <iostream>
using std::cout;
using std::endl;
using std::shared_ptr;
int main()
{
int ax = 0, bx = 0;
cout << &ax << " " << &bx << endl;//#1 007EFE74 007EFE68
shared_ptr<int> x(new int(ax));
shared_ptr<int> y(new int(std::move(bx)));
cout << x.get() <<" "<< y.get()<<endl;//#2 0092FDB8 0092FF98
return 0;
}
我写了一段代码验证也确实如此:
两个cout表明两个变量确实被重新拷贝到了堆内存中
请问动态内存是否是 只能拷贝不能移动,或者是我理解错了?