dimanche 31 juillet 2022

c++ design with unique_ptr with custom deleter

I am writing a tree data structure. Each node has a fixed size so I use a fixed size allocator for allocating/deallocating Node. This gives me a headache:

struct Node {
  // other attributes ...
  std::array<std::unique_ptr<Node, CustomDeleter>, num_children> children_;
};

Since all allocations/deallocations of Node are managed by my custom Alloc, I can't use std::unique_ptr<Node> for child nodes, I have to ship custom deleter (associated with that allocator) to children.

But Alloc must know the type of Node, because Alloc is a fixed-size allocator for Node, it should be aware of sizeof(Node) and alignof(Node).

But Node must know the type of Alloc, because CustomDeleter cannot be instantiated without Alloc! This is a circular depedency!

Have the C++ committee never considered about implementing a tree structure when they designed std::unique_ptr<Node, Deleter>? How can I resolve this problem?

ps. I can't use std::allocator<Node> because I should be able to use memory resource other than the default memory resource

Aucun commentaire:

Enregistrer un commentaire