我正在使用来自存储库的最新可用 GCC 构建。我决定使用它是因为一些额外的 C++0x 特性。但是现在我坚持了一些应该起作用的东西——我想通过 r 值添加新元素来映射。简化代码,演示问题:
#include <tr1/unordered_map>
class X
{
public:
X (void) { /* ... */ };
X (const X& x) = delete;
X (X&& x) { /* ... */ };
};
int main (void)
{
std::tr1::unordered_map<int, X> map;
// using std::tr1::unordered_map<int, X>::value_type didn't help too
std::pair<int, X> value (1, X ());
map.insert (std::move (value));
}
请注意,当用 int
等基本类型替换 X
类时,代码会编译并正常工作。
在我的生产代码中,对应于 X 的类也没有复制构造函数。
错误信息(就像所有与模板相关的错误一样)又长又难读,我不确定把它放在这里是否是个好主意。如果您需要错误消息,请通知我,因此我将更新此问题。消息的最后一部分很有趣:
(...)
/usr/include/c++/trunk/ext/new_allocator.h:106:9: error: use of deleted function ‘constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int, _T2 = X, std::pair<_T1, _T2> = std::pair<const int, X>]’
In file included from /usr/include/c++/trunk/utility:71:0,
from /usr/include/c++/trunk/tr1/unordered_map:34,
from kod.cpp:1:
/usr/include/c++/trunk/bits/stl_pair.h:110:17: error: ‘constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int, _T2 = X, std::pair<_T1, _T2> = std::pair<const int, X>]’ is implicitly deleted because the default definition would be ill-formed:
/usr/include/c++/trunk/bits/stl_pair.h:110:17: error: use of deleted function ‘X::X(const X&)’
此外,这应该有效,因为类似的错误已经修复 [C++0x] Implement emplace* in associative and unordered containers .
也许我做错了什么?在报告之前,我想确定这是 GCC 或 libstdc++ 错误。
最佳答案
除了使用 tr1 之外,您的代码在我看来是正确的。 tr1 限定的东西不知道右值引用或移动语义。
我获取了您的代码,从 header 和命名空间限定符中删除了 tr1,并使用 g++-4.4 和 libc++ (http://libcxx.llvm.org/) 成功编译了您的代码。尝试删除 tr1。
关于c++ - R 值插入不适用于 unordered_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4809868/