对于容器,例如 std::map< std::string, std::unique_ptr< Foo >>
, 它看起来像 emplace()
截至 gcc 4.7.2 尚未在 stdc++ 中实现。
不幸的是,我不能按值直接存储 Foo,因为它是一个抽象父类(super class)。
作为一个简单但低效的占位符,我一直在使用 std::map< std::string, Foo* >
结合 std::vector< std::unique_ptr< Foo >>
用于垃圾收集。
一旦 emplace() 可用,您是否有更高效且更容易替换的临时解决方案?
最佳答案
你需要 emplace()
做什么?只需将其移入:
#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;
}
事实上, you should not use emplace
with unique_ptr
's .
正如我在那里的评论中所指出的,我现在认为在用户代码中使用 new
是一个错误。它应该替换为 make_unique
,这样您就知道您的资源不可能泄漏:
// 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;
}
关于c++ - 用什么代替 std::map::emplace?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13784771/