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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM