C++ 新特性 移动构造函数和移动赋值

参考  https://blog.csdn.net/jujueduoluo/article/details/79107365

 

使用情景: 当进行拷贝构造函数的时候,如果传入的类型之后不使用了。

 

    //拷贝构造
    Tracer(const Tracer& t) {
        if (t.str != nullptr) {
            int len = strlen(t.str);
            str = new char[len + 1];        //重点!!!  传统拷贝构造函数,是新创建空间,然后把内容复制过去,也就是我们常说的深拷贝。
            strcpy_s(str, len+1, t.str);
        }
    }

    //移动构造
    Tracer(Tracer&& t)
    {
        if (t.str != nullptr)
        {
            str = t.str;      //重点!!!   只是把t的指针给this了, 然后t指向了nullptr
            t.str = nullptr;
        }
    }

    Tracer t1("Happy New Year!");
  Tracer t2(std::move(t1));

完整代码:

class Tracer
{
public:
    Tracer():str(nullptr){}
    Tracer(const char* s)
    {
        if (s != nullptr)
        {
            int len = strlen(s);
            str = new char[len + 1];        //array new
            strcpy_s(str, len+1, s);
        }
    }
    //拷贝构造
    Tracer(const Tracer& t) {
        if (t.str != nullptr) {
            int len = strlen(t.str);
            str = new char[len + 1];        //array new
            strcpy_s(str, len+1, t.str);
        }
    }
    //移动构造
    Tracer(Tracer&& t)
    {
        if (t.str != nullptr)
        {
            str = t.str;
            t.str = nullptr;
        }
    }

    Tracer& operator=(const Tracer& rhs)
    {
        if (this != &rhs)
        {
            free(str);
            if (rhs.str != nullptr)
            {
                int len = strlen(rhs.str);
                str = new char[len + 1];
                strcpy_s(str, len+1, rhs.str);
            }
        }
        return *this;
    }

    Tracer& operator=(Tracer&& rhs)
    {
        if (this != &rhs)
        {
            free(str);
            str = rhs.str;
            rhs.str = nullptr;
        }
        return *this;
    }

private:
    char* str;
};

int main()
{
    //效率对比
    DWORD start = GetTickCount();
    Tracer t1("Happy New Year!");

    for (int i = 0; i < 1000000; ++i) {
    
#ifndef STDMOVE
        Tracer t2(t1);
        Tracer t3;
        t3 = t2;
#else
        Tracer t2(std::move(t1));
        Tracer t3;
        t3 = std::move(t2);
#endif // !STDMOVE
    };
    DWORD end = GetTickCount();

    cout<<end-start<<endl;
    return 0;
}

posted @ 2020-02-16 22:26  StanK  阅读(1357)  评论(0编辑  收藏  举报