c++ - 包含 unique_ptr 的 unique_ptr
问题描述
免责声明:我起初写了一个我认为很清楚的问题版本,但那根本不是。我在这里将其重新设计为 MRE。
我有以下代码:
#include <map>
#include <memory>
#include <string>
using std::make_unique;
using std::string;
using std::unique_ptr;
template <typename T>
class Holder {
public:
Holder() {}
~Holder() {}
private:
T value_; // In real life, we can do something with this.
};
struct Thing {
Thing() {}
};
class ThingCollection {
public:
ThingCollection() {}
private:
// In real life, I have more maps of <string, Thing*>.
// Which is why I use a unique_ptr in the map.
std::map<string, unique_ptr<Thing>> the_map_;
};
我的问题是制作 a unique_ptr
,Holder<ThingCollection>
由于缺少复制构造函数而失败。
void foo() {
Holder<ThingCollection> cm; // OK.
auto cmp1 = make_unique<Holder<int>>(Holder<int>()); // OK.
auto cmp2 = make_unique<ThingCollection>(ThingCollection()); // OK.
auto cmp3 = make_unique<Holder<int>>(Holder<int>()); // OK.
auto cmp4 = make_unique<Holder<ThingCollection>>(Holder<ThingCollection>()); // BAD.
}
在编译时,由于复制构造函数 (of unique_ptr
) 被隐式删除,最后 (BAD) 行失败。我明白为什么unique_ptr
不可复制,但我不明白它为什么要在这里复制或正确的响应是什么。
我这样编译:
clang++ -std=c++14 -pthread -Wall -Wextra -c -o mre.o mre.cc
解决方案
当然,这会导致有关隐式删除的复制构造函数的错误。我想我明白为什么会这样
当您尝试复制具有不可复制成员的类型的对象时,通常会出现此类错误。
解决方案:不要尝试复制不可复制的对象。
免责声明:显然,unique_ptr 无法管理本身包含 unique_ptr 的东西,至少不是以任何幼稚的方式。
相反,唯一指针可以轻松管理本身包含唯一指针的东西。我能想到的幼稚方法会失败的唯一情况是指针形成递归链 - 本质上是一个链表 - 在这种情况下,您需要一个自定义析构函数来避免线性递归深度。
PS 而不是你的ThingCollection
课,我建议使用boost::multi_index_container
.
推荐阅读
- time-series - 如何对 AWS TimeStream 中的数据进行下采样
- excel - 根据列名删除指定列
- postgresql - 针对任意数据的 Postgres 全文搜索 - 可能与否?
- javascript - VueJS/Typescript - 找不到模块“./components/Navigation”或其相应的类型声明
- android - 如何使用 Stripe 在 Flutter 中不存卡的情况下进行支付?
- python - 未找到:在此服务器上未找到请求的 url。AWS django 弹性豆茎
- java - 当我尝试数元音和辅音时,似乎什么也没有发生
- c++ - 如何在 C++ 中打印许多具有名称及其对应值的变量?
- webots - 能耗微博电机
- java - Quarkus Microprofile Rest Client ResponseExceptionMapper 没有捕获错误