c++ - 用什么代替 std::map::emplace?

标签 c++ c++11 std

对于容器,例如 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/

相关文章:

c++ - 无法将变量 'test' 声明为抽象类型 'OurStack<int>'

c++ - C++ 中具有 std::vector 数据成员的 constexpr 成员函数

boost - 找到 map 中显示的 vector 元素

c++ - 将 volatile C 字符串与 std::cout 一起使用

c++ - 为什么这些 C++ STL 无序集不被视为相等?

c++ - 在 C++ 中使用抽象基类和模板进行重构

matplotlib 的 C++ 接口(interface)

c++ - 两个 nullptr 值相减保证为零?

c++ - 目前在 Ubuntu C/C++ 中如何将 IANA 时区名称转换为 UTC 偏移量

c++ - 我可以使用类类型来转换内存区域吗?