如何在我的向量实现中编写operator =(具有移动语义)和shrink_to_fit函数?

时间:2019-05-27 13:53:54

标签: c++

我有自己的向量类:

#include<iterator>
#include<memory>
#include<iostream>
#include<exception> 

using std::cout;
using std::endl;
using std::size_t;

template <class T> class vector
{
public:
    typedef T* iterator;
    typedef const iterator const_iterator;
    typedef size_t size_type;
    typedef T value_type;
    //------------------------------------------
    vector() { create(); }
    explicit vector(size_type n, const T& value = T{}) { create(n, value); }
    vector(const vector& a) { create(a.begin(), a.end()); }

和运算符:

    vector& operator=(const vector& a)
    {
        if (&a == this)  return *this;
        uncreate();
        create(a.begin(), a.end());
        return *this;
    }

vector& operator=(const vector&& a)
    {
        if (&a == this)  return *this;
        uncreate();

        //NEED TO WRITE SOME CODE HERE

    }
    ~vector() { uncreate(); } //destructor
    size_type size() const { return avail - data; }
    size_type capacity() const { return limit - data; }

私人班级成员:

  private:
  iterator data;
  iterator avail;
  iterator limit;

  std::allocator<T> alloc;
//--------------------------------
  void create()
  {
      data = avail = limit = nullptr;
  }

我应该用move(不知道如何写)和复制(已经完成)语义来写operator =。你能帮我吗?

1 个答案:

答案 0 :(得分:-1)

vector& operator=(vector&& a) noexcept
{
    a.swap(*this);
    return *this;
}

void swap(vector& otherVector) noexcept
{
   //swap all member variables here (I took some names that might not be the same, that you use)
   std::swap(otherVector.capacity, capacity);
   std::swap(otherVector.size,   size);
   std::swap(otherVector.buffer,   buffer);
}

这就是我的写法(不需要删除,因为它已被交换,因此当另一个向量超出范围时将被删除)

很明显,当您不希望使用交换函数时,也可以将交换函数所做的所有事情都放入移动赋值运算符中;)