繁体   English   中英

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

[英]How to make rvalue method correctly call move constructor

我有像这样的复制和移动构造函数的基类:

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

我添加了一个copy和move方法,以允许多态复制并从指针移动对象,该指针可以潜在地指向某些子类的实例。

但是当我写以下内容时

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

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

为什么构造函数重载不能正常工作,如何使它调用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限定不起作用。 (没有“指向右值的指针”或“指向左值的指针”,只有“指向const的指针”或“指向volatile的指针”等)。


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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