在类构造函数之外构造类实例的成员字段,由分配器分配但没有构造

问题描述 投票:0回答:0

我正在编写库容器的教育性 AllocatorAwareContainer 实现(列出并基于此 unordered_map)。在其中一个测试中使用了一个只能由特殊分配器构造的类。问题是我使用了一个类节点,它有一个成员字段这个类,我想构造这个成员字段。唯一的方法是使用特殊的分配器,但我没有找到使用分配器在构造函数中构造成员字段的方法。

我找到了另一种解决方案(不要单独构造Node和构造字段),但我不知道,这个程序是正确的还是UB。最好参考 C++ 标准

class Chaste {
 private:
  int x = 0;
  Chaste() = delete;
  Chaste(int x): x(x) {
    std::cout << "Chaste constructed by " << x;
  }
  // Nobody can construct me except this guy
  template<typename T>
  friend struct TheChosenOne;
};

template<typename T>
struct TheChosenOne: public std::allocator<T> {
  template<typename... Args>
  void construct(T* p, Args&&... args) const {
    new(p) T(std::forward<Args>(args)...);
  }
};
struct Node {
  Chaste ch;
  Node* next;
  Node* prev;
};
int main() {
  TheChosenOne<Node> alloc_node;
  TheChosenOne<Chaste> alloc_chaste;
  using alloc_traits_node = std::allocator_traits<TheChosenOne<Node>>;
  using alloc_traits_chaste = std::allocator_traits<TheChosenOne<Chaste>>;

  Node* node_ptr = alloc_traits_node::allocate(alloc_node, 1);
  alloc_traits_chaste::construct(alloc_chaste, &(node_ptr->ch), 42);
  // ... initializing pointers of Node
  // using these pointers and node->ch
  alloc_traits_chaste::destroy(alloc_chaste, &(node_ptr->ch));
  // should I call node_ptr->next and node_ptr->prev destructor?
  alloc_traits_node::deallocate(alloc_node, node_ptr, 1);
}
c++ constructor c++17 undefined-behavior allocation
© www.soinside.com 2019 - 2024. All rights reserved.