简体   繁体   中英

How to make rvalue method correctly call move constructor

I have base class with copy and move constructors like this:

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

I added a copy and move methods to allow polymorphic copying and moving the object from a pointer, that can potentialy point to an instance of some subclass.

However when i write the following

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

first case correctly calls copy constructor, but second case incorrectly calls copy constructor too.

Why does the constructor overloading not work properly and how do i make it to call the move constructor?

In the same way any rvalue reference parameter is an lvalue inside a function, the object for which an rvalue ref qualified member function is called is an lvalue within that member function.

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

Thus you need:

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

(Don't forget #include <utility> .)

The reason why *this is an lvalue is because pointer indirection always produces an lvalue where this is always a T* (or T cv * ) within a member function of a type T . While the member function cv qualification affects the this pointer, the ref qualification of the function does not. (There is no "pointer to rvalue" or "pointer to lvalue" but only "pointer to const" or "pointer to volatile" etc.)


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM