Search code examples
c++unique-ptrdeleted-functions

Error: Use of deleted function std::unique_ptr


I am trying to pass a unique_ptr into a custom vector class but I am receiving the error in the subject title.

I understand that you cannot copy a unique_ptr and so I am trying to use std::move() when passing it, however that doesn't seem to solve my problem... Where am I going wrong?

Thanks in advance

template<typename T>
class VectorSelectable {
public:
    void Add(const T& v) { 
        m_Items.push_back(move(v)); 
    }
private:
    vector<T> m_Items;
};

class FunctionType {
    int m_Data;
};

int main()
{
    VectorSelectable<unique_ptr<FunctionType>> vec;
    vec.Add(move(make_unique<FunctionType>()));
    return 0;
}

Edit: Added 'const' to 'Add(const T& v)'


Solution

  • If you want to allow both copy-via-const-ref and move-via-rvalue-ref, you can either template your Add method and use the universal forwarding reference technique, or write two overloads explicitly:

        void Add(const T& v) { 
            m_Items.push_back(v); 
        }
        void Add(T&& v) { 
            m_Items.push_back(std::move(v)); 
        }
    

    or

        template <typename U>
        void Add(U&& v) { 
            m_Items.push_back(std::forward<U>(v)); 
        }