1
#include <memory>
#include <list>
#include <unordered_map>
class ClsA {
};

typedef std::list<ClsA*> ClsAList;
typedef std::unordered_map< int, std::unique_ptr < ClsAList> > ClsAListMap;

ClsAListMap map;
void Insert(int id, ClsA *a) {          
    auto list = new ClsAList{ a };
    std::unique_ptr<ClsAList> smart_list(list);

    //compilation error here
    map.insert(id, smart_list);//error
    map.insert({ a, smart_list});//error
}

Due to the multi level of template, the error tip is not readable at all, what's wrong here?

By the way, how to use make_unique in this situation? I've try it without success, only lengthy error tip nightmares.

jw_
  • 1,663
  • 18
  • 32
  • Does this answer your question? [How do I pass a unique\_ptr argument to a constructor or a function?](https://stackoverflow.com/questions/8114276/how-do-i-pass-a-unique-ptr-argument-to-a-constructor-or-a-function) – jw_ Jan 18 '20 at 04:54

1 Answers1

1

There are two things you need to fix. The first is that you want to emplace the new element (you can use insert but it would be more involved). The second is that, since you can't copy the unique_ptr, you need to move it instead:

map.emplace(id, std::move(smart_list));

To use make_unique, you need to initialize the list a little differently:

auto list = std::make_unique<ClsAList>(1, a);

This uses the constructor that takes an initial number of elements to put in the list and the value to set them to.

Finally, those can be combined into one statement:

map.emplace(id, std::make_unique<ClsAList>(1, a));

Since the initial unique_ptr is a temporary, it will be moved from (automatically, since it is possible in this case).

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • I found that "map.emplace(id, std::unique_ptr(list));" is usable too. – jw_ Jan 18 '20 at 04:17
  • And "map.insert({ a, std::move(smart_list) });" can compile too, what about this? Indeed the OP itself have a extra error, the original idea is "map.insert({ a, smart_list})" which seems only need std::move to be right. – jw_ Jan 18 '20 at 04:42