【发布时间】:2020-01-27 15:39:19
【问题描述】:
这是一个示例代码:
struct T
{
T(int x) : x_(x)
{}
T(T&&) = delete;
T(const T&) = delete;
int x_;
};
int main()
{
std::unordered_map<int, T> m;
m.emplace(std::piecewise_construct, std::forward_as_tuple(1), std::forward_as_tuple(2));
m.emplace(std::piecewise_construct, std::forward_as_tuple(1), std::forward_as_tuple(2));
return 0;
}
第二个 emplace 失败,但 T 构造函数被调用了两次。我认为只有在可以插入时,那个 emplace 才会构造一个对象。你能解释一下吗?
编辑: 我使用 Visual Studio 2017 编译器。
【问题讨论】:
-
你确定吗?这仅显示了一次构造函数调用:wandbox.org/permlink/pAoaakc0p6ZyN2Xf 也许您应该添加有关编译器 inst 版本和系统的信息?
-
@MarekR
int main() 1: 1 T::T(int) x_: 2 int main() 2: 2 T::T(int) x_: 2等于调用了 2 个构造函数,不是吗? -
它不应该调用构造函数两次。这可能是您使用的 STL 实现的错误。在大多数情况下,这不是问题,并且可能会被优化掉,但仍然不应该发生这种情况。考虑将其作为错误报告发送给您使用的编译器。