I have following string& and unique_ptr&
const FilePath& path; // given as parameter
auto key = path.BaseName().value();
auto value = make_unique<SomeClass>();
I would like to use these in the following map
map<string, unique_ptr<SomeClass>> myMap;
When I do the following,
myMap.emplace(key, value);
I get this error:
note: in instantiation of function template specialization 'std::map<std::string, std::unique_ptr<SomeClass>>::emplace<const std::string &, std::unique_ptr<SomeClass> &>' requested here
I think this means that I am trying to put string& and unique_ptr& where string and unique_ptr is needed.
Would there be a way to use &-variable to a non-&-parameter?
Full code:
map<string, unique_ptr<SomeClass>> myMap;
void function (const FilePath& path) {
auto key = path.BaseName().value();
auto value = make_unique<SomeClass>();
myMap.emplace(key, value);
}
CodePudding user response:
std::unique_ptr
can't be copied, but only moved. You can use std::move
to convert value
to rvalue:
myMap.emplace(key, std::move(value));
CodePudding user response:
In this case you don't even need to use std::unique_ptr! Your map will own the instances of MyClass anyway. So why not make a map of SomeClass directly?
Don't dynamically allocate memory yourself unless you really have to.
#include <iostream>
#include <filesystem> // <== STL has its own filesystem
#include <map>
#include <string>
// do not use : using namespace std; !
class SomeClass
{
public:
explicit SomeClass(const int, const int ) {}
};
std::map<std::string_view, SomeClass> myMap;
void function(const std::filesystem::path& path)
{
auto key = path.filename();
myMap.emplace( key, 1, 2 ); // 1,2 are the parameters for constructor of SomeClass
}