如何在我自己的类Vector中使用Move构造函数而不是Move赋值运算符?

时间:2017-03-26 23:19:35

标签: c++ c++11 vector move-semantics

我有自己的类Vector,它实现了移动构造函数,移动赋值运算符和方法push_back for rvalue

template<typename T>
class Vector
{
private:
    T* buffer;
    size_t size;
    size_t capacity;
public:
    Vector(size_t s) {
        size = 0;
        capacity = s;       
        buffer = new T[capacity];
    }
    //Move constructor
    Vector(Vector&& tmp): buffer(tmp.buffer),
                          size(tmp.size),
                          capacity(tmp.capacity)
    {
        tmp.buffer = nullptr;
    }
    //Move assignment operator
    Vector& operator=(Vector&& tmp) {
        size = tmp.size;
        capacity = tmp.capacity;
        buffer = std::move(tmp.buffer);
        tmp.buffer = nullptr;
        return *this;
    }
    void push_back(const Vector<T>& v) {
        if (size >= capacity)
            reserve(capacity + 5);
        buffer[size++] = v;
    }
    //push_back for rvalue
    void push_back(T&& v) {
        if (size >= capacity)
            reserve(capacity + 5);
        buffer[size++] = std::move(v);
    }
    ~Vector() {
        delete[] buffer;
    }

方法push_back(T&amp;&amp; v)行

buffer[size++] = std::move(v);

使用Move赋值运算符。 如何更改代码以便使用Move constructror?

2 个答案:

答案 0 :(得分:3)

使用placement new

ruby

以下是一个完整的示例:http://cpp.sh/6s4i3

答案 1 :(得分:0)

我正在移动球但是如果有什么有用的东西

scanf