Home > Enterprise >  Error: Use of deleted function std::unique_ptr
Error: Use of deleted function std::unique_ptr

Time:12-02

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)'

CodePudding user response:

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)); 
    }

CodePudding user response:

The Add() accepts an lvalue reference of T, but move(make_unique<FunctionType>()) returns an rvalue reference, you cannot bind an rvalue to an lvalue reference.

You can turn Add() into a template function and use forwarding references to accept lvalues and rvalues and move them into your m_Items.

template<class U>
void Add(U&& v) { 
    m_Items.push_back(move(v)); 
}

Demo.

CodePudding user response:

@Max Peglar-Willis The problem here is that somewhere, your code is attempting to call the "copy-assignment" operator.

This causes the compiler to attempt to generate a copy-assignment operator which calls the copy-assignment operators of all the subobjects. Eventually, this leads to an attempt to copy a unique_ptr,

an operation that is not possible.

  • Related