首页 > 解决方案 > 指针可以自己移动到容器吗?

问题描述

这是这个问题的延续,但我不想使用自定义删除器。我有以下界面:

struct Interface {
  Interface(const Interface &) = delete;
  auto operator=(const Interface &) -> Interface & = delete;
  ~Interface() = 0;
  protected:
    Interface() = default;
};

和一个实现:

struct Implementation : public Interface {
  Implementation(Pool &p) : m_pool{p} {}
  Pool &m_pool;
};

我还有一个实现池:

struct Pool {
  auto get() -> std::unique_ptr<Interface>;
  std::vector<std::unique_ptr<Interface>> m_objects;
};

我的问题是,是否可以将Implementation, 实例化为指向 的指针Interface,在调用其析构函数时将其自身移动到池中?

标签: c++c++11

解决方案


我认为您可以通过创建包装器来实现它。这有点像从池中借用一个对象,一旦包装的对象超出范围,该对象就会放回池中。

struct PooledObject {
  PooledObject(Pool& pool, std::unique_ptr<Interface> object) 
        : m_object(std::move(object)), m_pool(pool) {}
  ~PooledObject() {
       m_pool.put(std::move(m_object));
   }
  // implement -> for easy access to underlying object
  std::unique_ptr<Interface> m_object;
  Pool& m_pool;
};

struct Pool {
  auto get() -> PooledObject;
  void put(std::unique_ptr<Interface> object);
}

推荐阅读