重学C++ 移动语义

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/artisans/article/details/81261297

#include "iostream"
#include "vector"
#include <algorithm>
using namespace std;

class Test
{
public:
    Test() = default;

    Test(const Test& t) = default;

    Test(Test&& t)
    {
        if (this == &t) return;

        this->x = t.x;
        this->y = t.y;
        this->z = t.z;
        this->ptr = t.ptr;
        t.ptr = nullptr;

        cout << "Test(Test&& t)   " << endl;
    }

    int x, y;
    int z;
    char* ptr;
};

Test foo(Test t2)
{
    return t2;
}

int main()
{
    Test t2;
    t2.x = 1;
    t2.y = 2;
    t2.z = 3;

    Test t = foo(t2);

    cout << t.x << "  " << t.y << "  " << t.z << endl;

    getchar();
    return 0;
}


这里写图片描述

猜你喜欢

转载自blog.csdn.net/artisans/article/details/81261297