【发布时间】:2020-08-16 12:47:41
【问题描述】:
制作一个只移动类型的映射向量在 Windows 上似乎无法正常工作。 在此处查看代码:https://godbolt.org/z/yAHmzh
#include <vector>
#include <map>
#include <memory>
// vector<vector<move-only>> works
void foo() {
std::vector<std::vector<std::unique_ptr<int>>> outer;
std::vector<std::unique_ptr<int>> inner;
std::unique_ptr<int> p = std::make_unique<int>(1);
inner.push_back(std::move(p));
outer.push_back(std::move(inner));
}
// vector<map<move-only>> fails to compile upon inserting an element.
void bar() {
std::vector<std::map<std::unique_ptr<int>, std::unique_ptr<int>>> vec;
std::map<std::unique_ptr<int>, std::unique_ptr<int>> map;
std::unique_ptr<int> p1 = std::make_unique<int>(1);
std::unique_ptr<int> p2 = std::make_unique<int>(2);
map.insert(std::make_pair(std::move(p1), std::move(p2)));
// The following line fails to compile on windows. It errors with a message about
// the unique_ptr copy constructor being explicitly deleted. This seems to only happen
// on windows. GCC and clang have no problem with this.
vec.push_back(std::move(map));
}
int main(int argv, char** argc)
{
foo();
bar();
}
GCC 和 Clang 对该代码没有问题,但 MSVC 无法编译。
寻找一种解决方法,让我这样做可以在所有主要编译器上编译。
【问题讨论】:
标签: c++ vector visual-c++ move-semantics