简体   繁体   中英

C++ nested map with unique_ptr

I'm currently learning c++ and focusing on the STL. I didn't find the answer to this problem, so here is the issue: how to set elements in the data structure map<int, map<string, vector<unique_ptr>>> ? The following code with some comments illustrates this problem:

#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 
}

-- edit: link to the compilation erros: ideone.com/hs3G8m

My question is how to initialize and add elements to the structure map<int, map<string, vector<unique_ptr<T>>>> . I'm using GCC 4.9 with c++11 flag. Thanks in advance!

I do not see any problems with the code. I have compiled it as

g++ -Wall -std=c++11 test.cpp
without any warnings using
 gcc (GCC) 4.8.1  

It looks like a compiler/STL bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM