vendredi 21 février 2020

Should I implement rvalue push function and should I use std::move?

As an exercise, I'm implementing a stack class in C++11.
This is the relevant code:

template <class T>
class stack
{
private:
    T * elements;
    std::size_t capacity;
    std::size_t count;

public:
    explicit stack(std::size_t capacity) : capacity(capacity)
    {
        elements = new T[capacity];
    };

    ~stack()
    {
        delete[] elements;
    };

    void push(const T & t)
    {
        if (capacity > count)
        {
            elements[count++] = t;
        }
    }

    void push(T && t)
    {
        if (capacity > count)
        {
            elements[count++] = std::move(t);
        }
    }
};

I'm using the class as following:

stack<std::string> stack_test(2);
stack_test.push("string1");

std::string string2 = "string2";
stack_test.push(string2);

As expected, the first push uses push(T && t), while the second push uses push(const T & t).

Should I implement the rvalue push?
And should I use std::move() in that?

Aucun commentaire:

Enregistrer un commentaire