C ++在地图中插入unique_ptr
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16923748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ inserting unique_ptr in map
提问by vigs1990
I have a C++ object of type ObjectArray
我有一个 C++ 类型的对象 ObjectArray
typedef map<int64_t, std::unique_ptr<Class1>> ObjectArray;
What is the syntax to create a unique_ptr
to a new object of type Class1
and insert it into an object of type ObjectArray
?
unique_ptr
为类型为新的对象创建 aClass1
并将其插入到类型为的对象中的语法是什么ObjectArray
?
回答by Andy Prowl
As a first remark, I wouldn't call it ObjectArray
if it is a map and not an array.
首先,ObjectArray
如果它是地图而不是数组,我不会调用它。
Anyway, you can insert objects this way:
无论如何,您可以通过以下方式插入对象:
ObjectArray myMap;
myMap.insert(std::make_pair(0, std::unique_ptr<Class1>(new Class1())));
Or this way:
或者这样:
ObjectArray myMap;
myMap[0] = std::unique_ptr<Class1>(new Class1());
The difference between the two forms is that the former will fail if the key 0
is already present in the map, while the second one will overwrite its value with the new one.
两种形式的区别在于,如果键0
已经存在于映射中,前一种将失败,而第二种形式会用新的键覆盖其值。
In C++14, you may want to use std::make_unique()
instead of constructing the unique_ptr
from a new
expression. For instance:
在 C++14 中,您可能希望使用std::make_unique()
而不是unique_ptr
从new
表达式构造。例如:
myMap[0] = std::make_unique<Class1>();
回答by Saurabh
If you want to add an existing pointer to insert into the map, you will have to use std::move.
如果要添加现有指针以插入到地图中,则必须使用 std::move。
For example:
例如:
std::unique_ptr<Class1> classPtr(new Class1);
myMap.insert(std::make_pair(0,std::move(classPtr)));
回答by antonpp
In addition to previous answers, I wanted to point out that there is also a method emplace
(it's convenient when you cannot/don't want to make a copy), so you can write it like this:
除了前面的答案,我想指出还有一个方法emplace
(当你不能/不想复制时很方便),所以你可以这样写:
ObjectArray object_array;
auto pointer = std::make_unique<Class1>(...); // since C++14
object_array.emplace(239LL, std::move(pointer));
// You can also inline unique pointer:
object_array.emplace(30LL, std::make_unique<Class1>(...));