简体   繁体   English

C ++在地图中插入unique_ptr

[英]C++ inserting unique_ptr in map

I have a C++ object of type ObjectArray 我有一个ObjectArray类型的C ++对象

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 ? Class1类型的新对象创建unique_ptr并将其插入ObjectArray类型的对象的语法是什么?

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. 在C ++ 14中,您可能要使用std::make_unique()而不是根据new表达式构造unique_ptr For instance: 例如:

myMap[0] = std::make_unique<Class1>();

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)));

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>(...));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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