How can I fix this error 'no matching function for call'?

Viewed 1674

Given the following code:

    std::map<std::string, std::unique_ptr<Obj>> objs;
    std::string str;
    Obj obj;
    std::unique_ptr<Obj> objUniquePtr = std::unique_ptr<Obj>(new Obj(obj));
    objs.insert({ str, objUniquePtr });   <<<<<<<< ERROR

I get the following error:

no matching function for call to 'std::map<std::__cxx11::basic_string<char>, std::unique_ptr<Obj> >::insert(<brace-enclosed initializer list>)'

How can I fix this error?

1 Answers

You're attempting to copy construct a std::unique_ptr, which is not allowed since std::unique_ptrs cannot be copy constructed. Move construct it instead and use the emplace member function, to make sure no copy construction of a std::unique_ptr takes place:

objs.emplace({str, std::move(objUniquePtr)}); //notice the move operation

This will solve your error. Just make sure you don't try to access or dereference objUniquePtr after the move operation, as you'll be trying to dereference a nullptr.

Related