Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::move or std::forward with parameter std::unique_ptr<T>&&

Tags:

c++

c++11

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++.

like image 537
keith Avatar asked Dec 15 '15 12:12

keith


1 Answers

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.

like image 52
TartanLlama Avatar answered Sep 23 '22 15:09

TartanLlama