【发布时间】:2017-04-02 10:58:54
【问题描述】:
我有这样的复制和移动构造函数的基类:
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:哦,我忘了。但在这两种情况下它仍然调用复制构造函数。
-
return new Test(std::move(*this));
标签: c++ constructor move-semantics