Puntos de conocimiento de objetos en movimiento

"Lenguaje de programación C ++ (cuarta edición)" Capítulo 3.3.2, Capítulo 17.5.2

1. El constructor de movimiento es un tipo de constructor que construye un objeto moviendo los recursos de otros objetos.

#define debug qDebug()<<

struct ceshi
{
    int frist;
    int second;
    ceshi(int one = 0,int two = 0):frist{one},second{two}
    {
    }

    ceshi(ceshi && c):frist{c.frist},second{c.second}
    {
        debug "调用移动构造";
        c.frist = -1;
        c.second = -1;
    }
};

int main(int argc, char *argv[])
{
    ceshi a(4,5);
    ceshi b = std::move(a);

    debug a.frist << a.second << &a;
    debug b.frist << b.second << &b;
}

2 、 estándar :: mover () 

La función de esta función es solo obtener la referencia rvalue, aunque el nombre de la función se llama mover, no mueve nada.

    ceshi b = std::move(a);

Escribir de esta manera llamará al constructor de movimiento y pasará la referencia rvalue obtenida como parámetro.

3. Si el constructor de movimiento no está definido en la clase, esto llamará al constructor de copia:

#define debug qDebug()<<
struct ceshi
{
    int frist;
    int second;
    ceshi(int one = 0,int two = 0):frist{one},second{two}
    {
    }

    ceshi(const ceshi & c)
    {
        this->frist = c.frist;
        this->second = c.second;
        debug "调用拷贝构造函数";
    }
};

int main(int argc, char *argv[])
{
    ceshi a(4,5);
    ceshi b = std::move(a);

    debug a.frist << a.second;
    debug b.frist << b.second;
}

Supongo que te gusta

Origin blog.csdn.net/kenfan1647/article/details/113790669
Recomendado
Clasificación