C++使用记录002——使用右值拷贝构造函数操作双向链表

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <deque>
#include <algorithm>

#include <math.h>

using namespace std;

class LinkedList
{
    char m_arrayData[10] = "List";
    std::vector<int> m_vectorData;
public:
    LinkedList *m_last = nullptr;
    LinkedList *m_next = nullptr;
public:
    LinkedList(int id)
    {
        for (int i = 0; i < 5; ++i)
            m_vectorData.push_back(i + id);
        m_arrayData[4] = id & 0x7F;
        m_arrayData[5] = '\x0';
    }
    LinkedList(const LinkedList &ll) = delete;
    LinkedList& operator=(const LinkedList &ll) = delete;
    LinkedList(LinkedList &&ll) = default;
    LinkedList& operator=(LinkedList &&ll) = default;
    ~LinkedList()
    {
        if (nullptr != m_last)
        {
            m_last->m_next = nullptr;
            delete m_last;
            m_last = nullptr;
        }
        if (nullptr != m_next)
        {
            m_next->m_last = nullptr;
            delete m_next;
            m_next = nullptr;
        }
    }
    void CreateNext()
    {
        m_next = new LinkedList(m_vectorData[0] + 1);
        m_next->m_last = this;
    }
    void ToNext();
    void ToLast();
};

static LinkedList CacheForSwap(10);

void LinkedList::ToNext()
{
    auto pNext = m_next;
    CacheForSwap = std::move(*this);
    *this = std::move(*pNext);
    *pNext = std::move(CacheForSwap);
    this->m_last = pNext;
    pNext->m_next = this;
    // 避免在CacheForSwap析构时错误的重新对已经释放的内存进行释放
    CacheForSwap.m_next = nullptr;
    CacheForSwap.m_last = nullptr;
}

void LinkedList::ToLast()
{
    auto pLast = m_last;
    CacheForSwap = std::move(*this);
    *this = std::move(*pLast);
    *pLast = std::move(CacheForSwap);
    this->m_next = pLast;
    pLast->m_last = this;
    CacheForSwap.m_next = nullptr;
    CacheForSwap.m_last = nullptr;
}

int main()
{
    LinkedList ll(0);
    ll.CreateNext();
    ll.ToNext();
    ll.ToLast();

    cin.get();

    return 0;
}

接下来就可以对这个数据模型很快速的进行前后移动了,在实际应用中被我当作关卡存储的数据模型

默认的右值拷贝构造函数能够将数组的值也全部拷贝过去是开始有疑问的地方,测试之后就放心了

3 thoughts on “C++使用记录002——使用右值拷贝构造函数操作双向链表

发表评论