What do you need emplace() ? Just move it:
#include <iostream> #include <map> #include <memory> #include <string> struct Foo { virtual ~Foo() = default; virtual std::string name() const = 0; }; struct Bar : Foo { std::string name() const { return "Bar"; } }; int main() { std::map<std::string, std::unique_ptr<Foo>> m; std::unique_ptr<Foo> p(new Bar()); m.insert(std::make_pair("a", std::move(p))); std::cout << m["a"]->name() << std::endl; }
In fact, you should not use emplace with unique_ptr .
As noted in my comment, I am now considering using new in user error code. It should be replaced with make_unique , so you know that your resource cannot flow:
// will be in std:: someday template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } int main() { std::map<std::string, std::unique_ptr<Foo>> m; m.insert(std::make_pair("a", make_unique<Bar>())); std::cout << m["a"]->name() << std::endl; }
source share