在此示例中,有问题的行是 Basket
的 repo
成员的声明
#include <vector>
#include <string>
#include <memory>
#include <unordered_map>
struct Product {
std::unique_ptr<std::string> description;
};
struct Basket {
// this line is OK, just moves it
std::vector<Product> ps;
// Doesn't compile with this line uncommented ! Can't move map ?
// std::unordered_map<std::string, Product> repo;
};
int main(int argc, const char *argv[]) {
std::vector<Basket> baskets;
Basket b1;
baskets.push_back(std::move(b1));
return 0;
}
当repo
成员声明被取消注释时,我会收到可怕的错误表。
在 gcc 4.7.2 和 Clang 3.3 上测试并得到相同的错误:
error: call to implicitly-deleted copy constructor of 'Product'
... lot of similar stuff ...
最佳答案
这是 libstdc++ 中未实现的功能。
我检查了 GCC 4.7.2 的 header ,unordered_map
甚至没有移动构造函数/赋值运算符。他们可能已将其向后移植到 4.7.3,但无论哪种方式,您都必须升级编译器和/或 libstdc++ 才能编译该行。
使用足够新的 libstdc++ 可以很好地编译:http://goo.gl/16Vnrj
关于C++11 无法移动内部有 unordered_map 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20257713/