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

C++: use string& and unique_ptr<SomeClass>& for map<string, unique_ptr<SomeClass>>

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,

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

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

>Solution :

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