如何使右值方法正确调用移动构造函数

How to make rvalue method correctly call move constructor

我的基础 class 具有复制和移动构造函数,如下所示:

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;
};

我添加了复制和移动方法以允许从指针多态复制和移动对象,这可能指向某个子实例class。

但是当我写下下面的内容时

Test t1( 5 );
Test * t2 = t1.copy();
Test * t3 = Test( 6 ).move();

第一种情况正确调用了复制构造函数,但第二种情况也错误地调用了复制构造函数。

为什么构造函数重载不能正常工作,我如何让它调用移动构造函数?

与任何右值引用参数在函数内都是左值一样,调用右值引用限定成员函数的对象也是该成员函数内的左值。

void foo(Test&& x) 
{ 
    /* here x is an lvalue ! */ 
    Test y(std::move(x)); // need explicit cast to actually move
}

因此你需要:

virtual Test * move() && {
    return new Test( std::move(*this) );
}

(别忘了#include <utility>。)

*this 是左值的原因是因为指针间接总是产生一个左值,其中 this 总是成员函数中的 T*(或 T cv *T 类型。虽然成员函数 cv 限定会影响 this 指针,但函数的 ref 限定不会。 (没有"pointer to rvalue"或"pointer to lvalue",只有"pointer to const"或"pointer to volatile"等)


  • Rvalue reference: Why aren't rvalues implicitly moved?
  • C++ move constructor not called for rvalue reference
  • What is "rvalue reference for *this"?