Knowledge points of moving objects

"C++ Programming Language (Fourth Edition)" Chapter 3.3.2, Chapter 17.5.2

1. The move constructor is a type of constructor, which constructs an object by moving the resources of other objects.

#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、std::move() 

The function of this function is only to get the rvalue reference. Although the function name is called move, it does not move anything.

    ceshi b = std::move(a);

Writing this way will call the move constructor and pass the obtained rvalue reference as a parameter.

3. If the move constructor is not defined in the class, this will call the copy constructor:

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

Guess you like

Origin blog.csdn.net/kenfan1647/article/details/113790669