Search code examples
c++c++11move-semanticsrvalue-reference

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 (i.e. is push(T && t) needed to be implemented)?
And should I use std::move() in that?


Solution

  • Given that you are storing t in both pushes, you can have one

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

    But really, you should be using std::vector<T> elements; (or std::deque / std::list), like how std::stack does