7

I have the following template class (stripped down to contain only the relevant parts) with a method called Push written in C++ 11:

template<class T, int Capacity>
class CircularStack
{
private:
    std::array<std::unique_ptr<T>, Capacity> _stack;

public:
   void Push(std::unique_ptr<T>&& value)
   {
      //some code omitted that updates an _index member variable

      _stack[_index] = std::move(value);
   }
}

My question is:

Should I be using std::move or std::forward within Push?

I am not sure whether std::unique_ptr<T>&& qualifies as a universal reference and therefore should be using forward rather than move.

I am reasonably new to C++.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
keith
  • 5,122
  • 3
  • 21
  • 50
  • If you are comming from a manged language, try not to imitate a "reference to-" approach. In C++, array of object should be in most cases an array of object, not an array of references which is populated dynamically with `new`. keep that in mind. – David Haim Dec 15 '15 at 12:13
  • Duplicates: http://stackoverflow.com/q/9671749, http://stackoverflow.com/q/7257144. – Kerrek SB Dec 15 '15 at 12:14
  • Thanks for the tip, would `std::unique_ptr` be OK given `Push` will be given instances of types that inherit `T`? – keith Dec 15 '15 at 12:19
  • @keith Yes, `std::unique_ptr` is reasonable for containers which own polymorphic types, like the situation you describe. – TartanLlama Dec 15 '15 at 13:39

1 Answers1

9

You should use std::move.

std::unique_ptr<T>&& is an rvalue reference, not a forwarding reference*. Forwarding references in function parameters must look like T&& where T is deduced, i.e. a template parameter of the function being declared.

* forwarding reference is the preferred name for what you call a universal reference.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193