dimanche 26 mars 2017

How can I use Move constructor instead of Move assignment operator in my own class Vector?

I have my own class Vector which implements Move constructor, Move assignment operator and method 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;
    }

In method push_back(T&& v) the line

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

uses Move assignment operator. How can I change code so that it will use Move constructror ?

Aucun commentaire:

Enregistrer un commentaire