繁体   English   中英

std::map emplace 不可移动不可复制非默认可构造类型

[英]std::map emplace non-movable non-copyable non-default-constructible type

我想要一个 class 的 map,它没有复制 ctor、移动 ctor 和默认 ctor(我无法控制此类)。

我已经尝试使用 std::map::emplace 与 std::piecewise_construct 和 std::forward_as_tuple arguments,但似乎编译器告诉我这是不可能的,因为它首先尝试默认构造。

// Example program
#include <iostream>
#include <string>
#include <map>
#include <utility>
#include <tuple>

class stone
{
public:
    stone() = delete;
    stone(stone& s) = delete;
    stone(stone&& s) = delete;
    stone(const std::string& s) : str(s)
    {
    }
    std::string str;
};

int main()
{
    std::map<int, stone> m;
    m.emplace(std::piecewise_construct, std::forward_as_tuple(5), std::forward_as_tuple("asdf"));
    std::cout << "map[5]: " << m[5].str << "\n";
}

在此处查看带有编译器错误的示例: http://cpp.sh/8bbwh

我怎样才能使这项工作? 我试过查看类似的问题,但它们似乎不包含任何对我非常具体的场景有用的答案。

std::map emplace 不可移动不可复制非默认可构造类型

像这样:

m.emplace(5, "asdf");

不需要 std::piecewise_construct 也不需要 std::forward_as_tuple。


至于查找值,您不能使用下标运算符,因为这要求类型是默认可构造的 - 当查找前 map 中的值不存在时,将使用默认构造。

要查找非默认可构造类型,您必须使用 map::find 或 map::at 代替。 前者将迭代器返回到结束,后者如果映射的值不存在则抛出异常。

emplace 操作没有问题,但是,问题在于std::map::operator[]因为它要求value_type是默认可构造的。 但是, stone有一个已删除的默认构造函数。

相反,您可以使用没有该要求std::map::at

std::cout << "map[5]: " << m.at(5).str << "\n";

这是一个演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM