首页 > 解决方案 > 包含 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_ptrHolder<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

标签: c++c++14unique-ptr

解决方案


当然,这会导致有关隐式删除的复制构造函数的错误。我想我明白为什么会这样

当您尝试复制具有不可复制成员的类型的对象时,通常会出现此类错误。

解决方案:不要尝试复制不可复制的对象。


免责声明:显然,unique_ptr 无法管理本身包含 unique_ptr 的东西,至少不是以任何幼稚的方式。

相反,唯一指针可以轻松管理本身包含唯一指针的东西。我能想到的幼稚方法会失败的唯一情况是指针形成递归链 - 本质上是一个链表 - 在这种情况下,您需要一个自定义析构函数来避免线性递归深度。

PS 而不是你的ThingCollection课,我建议使用boost::multi_index_container.


推荐阅读