C++嵌套unique_ptr的map

4

我目前正在学习C++,并专注于STL。我没有找到这个问题的答案,所以问题是:如何设置数据结构map<int,map<string,vector<unique_ptr>>>中的元素?以下带有一些注释的代码说明了这个问题:

#include <map>
#include <string>
#include <memory>
#include <vector>

using namespace std;

// Used in the example
struct Resource {};

int main(int argc, char** argv) {
  // I was able to get the following map running fine
  // int -> { string -> unique_ptr }
  map<int, map<string, unique_ptr<Resource>>> data;

  map<string, unique_ptr<Resource>> toBeInserted;
  toBeInserted["key"] = unique_ptr<Resource>(new Resource);
  // data[1] = toBeInserted; // error
  data[1] = std::move(toBeInserted); // ok


  // But the issue happens when it's a vector of unique_ptrs
  // int -> { string -> { [unique_ptr] } }
  map<int, map<string, vector<unique_ptr<Resource>>>> otherData;

  vector<unique_ptr<Resource>> list;
  list.push_back(unique_ptr<Resource>(new Resource));
  list.push_back(unique_ptr<Resource>(new Resource));

  map<string, vector<unique_ptr<Resource>>> _toBeInserted;
  _toBeInserted["key"] = std::move(list); // ok

  // But I cant insert _toBeInserted back to the original map.
  // The compilation errors are all related to the unique_ptr 
  otherData[1] = std::move(_toBeInserted); // Can't do this 
}

-- 编辑:编译错误链接:ideone.com/hs3G8m

我的问题是如何初始化并向结构体map<int, map<string, vector<unique_ptr<T>>>>中添加元素。我正在使用带有c++11标志的GCC 4.9。提前感谢!


vector<unique_ptr<Resource>> list;建议不要将变量命名为STL类的名称,例如 list - PaulMcKenzie
1
你为什么在这里使用 unique_ptr?如果你将一个 unique_ptr 放入一个 vector 中,那么当你想要解引用它时,你必须先将其移出,因为你不允许制作重复的副本。看起来 shared_ptr 是你尝试实现的适当类型。 - Saran Tunyasuvunakool
在我的代码中,描述的地图是一个类的成员,该类管理一些资源并根据这些资源执行一些操作。最初它只是一组资源的向量,但为了找到它们,它在列表中进行了线性搜索。我尝试通过将资源的属性嵌套在地图中来进行优化(这有意义吗?)。管理器实际上拥有它执行任务所需的所有资源。 - user3696012
@WhozCraig Coliru的clang++似乎正在使用GCC的STL。在Mac OS X上,OP的代码实际上可以使用-std=c++11clang++和Intel的icpc上编译通过。这两个都使用Clang的STL。看起来像是GCC的STL中的一个错误?(另外,我收回了关于此处unique_ptr有效性的评论:只要OP在从map中取出指针时不尝试“别名”它,就可以使用) - Saran Tunyasuvunakool
我使用g++ 4.4 (-std=c++0x)编译了代码,没有任何问题。你的设置可能有问题。 - rkachach
显示剩余5条评论
1个回答

2

我没有看到代码有任何问题。 我已经使用

gcc (GCC) 4.8.1
编译了代码,命令为
g++ -Wall -std=c++11 test.cpp
,没有任何警告。

看起来像是编译器或STL的bug。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接