考虑这段代码:
#include <iostream>
#include <string>
using namespace std;
class Movable {
public:
Movable(const string& name) : m_name(name) { }
Movable(const Movable& rhs) {
cout << "Copy constructed from " << rhs.m_name << endl;
}
Movable(Movable&& rhs) {
cout << "Move constructed from " << rhs.m_name << endl;
}
Movable& operator = (const Movable& rhs) {
cout << "Copy assigned from " << rhs.m_name << endl;
}
Movable& operator = (Movable&& rhs) {
cout << "Move assigned from " << rhs.m_name << endl;
}
private:
string m_name;
};
int main() {
Movable obj1("obj1");
Movable obj2(std::move(obj1));
obj2 = std::move(obj1); // For demostration only
const Movable cObj("cObj");
Movable tObj(std::move(cObj));
tObj = std::move(cObj); // For demonstration only
}
它的输出是:
Move constructed from obj1
Move assigned from obj1
Copy constructed from cObj
Copy assigned from cObj
如您所见,在这些行中,
Movable tObj(std::move(cObj));
tObj = std::move(cObj); // For demonstration only
我打算移动cObj
到tObj
(使用赋值运算符的第二步纯粹是为了演示)。但是,正如您在输出中看到的,cObj
仅复制到tObj
.
上面的例子只是一个演示,我不知道这有什么实际用途。但我会问:
- 我可以移动一个
const
物体吗? - 如果可以,这样做安全吗?
补充:我忘了问。如果我可以移动一个const
物体,我应该怎么做?( const_cast
?)