Kel*_*tek 4 c++ unordered-map unique-ptr c++11 c++14
该代码段似乎不起作用,因为唯一指针被存储到pair对象中,然后试图从其中复制。可以避免吗?
std::unordered_map<std::string,std::unique_ptr<int>> _map {
{"hello", std::make_unique<int>(7)}
};
Run Code Online (Sandbox Code Playgroud)
完整的代码示例和编译错误可以在这里查看http://cpp.sh/7uc3a
小智 5
Yes, by not using list-initialization.
std::unordered_map<std::string,std::unique_ptr<int>> _map;
_map.insert({"hello", std::make_unique<int>(7)});
Run Code Online (Sandbox Code Playgroud)
std::unordered_map needs to call either the copy or move constructor in order to store any keys and values in its internal buffer. In the case of std::unique_ptr, the copy destructor is deleted, since making a copy of a std::unique_ptr would make it, well, not unique. That leaves only the move constructor.
The problem is with how you're initializing your map:
std::unordered_map<std::string,std::unique_ptr<int>> _map {
{"hello", std::make_unique<int>(7)}
};
Run Code Online (Sandbox Code Playgroud)
You're initializing your map's values using a std::initializer_list.
From cppreference:
An object of type std::initializer_list is a lightweight proxy object that provides access to an array of objects of type const T.
Effectively, all of the values in your initializer list are const. That means the move constructor on your std::unique_ptr can't be called, since moving an object generally requires modifying the original instance. Since the std::unique_ptr can't be moved, the compiler falls back on the copy constructor, which is why it ends up complaining that the copy constructor is deleted.
The snippet I posted works because insert accepts a non-const std::pair, which means that the std::unique_ptr is non-const, and can have its move constructor called.
| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |