ruipacheco
ruipacheco

Reputation: 16442

Can a pointer move itself to a container?

This is a continuation of this question but I don't want to use a custom deleter. I have the following interface:

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

And an implementation:

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

I also have a pool of Implementations:

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

My question is if it is possible to have the Implementation, instantiated as a pointer to Interface, move itself into the pool when its destructor is called?

Upvotes: 0

Views: 130

Answers (1)

gkamal
gkamal

Reputation: 21000

I think you can achieve it by creating a wrapper. It is kind of like borrowing an object from the pool which will then be put back into the pool once the wrapped object goes out of scope.

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

Upvotes: 3

Related Questions