我有複製和移動構造這樣的基類:如何使右值方法正確調用移動的構造
class Test {
public:
Test(int i) {
iptr = new int(i);
}
Test(const Test & other) {
printf("copy constructor\n");
iptr = new int(*other.iptr);
}
Test(Test && other) {
printf("move constructor\n");
iptr = other.iptr;
other.iptr = NULL;
}
virtual ~Test() {
delete iptr;
}
virtual Test * copy() {
return new Test(*this);
}
virtual Test * move() && {
return new Test(*this);
}
protected:
int * iptr;
};
我加入了複製和移動方法來允許多態複製和從一個指針移動對象,這可能會潛在地指向某個子類的一個實例。
但是當我寫了下面的
Test t1(5);
Test * t2 = t1.copy();
Test * t3 = Test(6).move();
第一種情況下正確地調用拷貝構造函數,但第二種情況下錯誤地調用拷貝構造函數了。
爲什麼構造函數重載不能正常工作,我該如何調用移動構造函數?
爲什麼你不把標籤拷貝方法作爲const標記到它的實例? –
@LaurentG:哦,我忘了。但在這兩種情況下它仍然調用複製構造函數。 – Youda008
'return new Test(std :: move(* this));' – Pixelchemist