Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)); 
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading