'How to construct an class template with std::allocator construct

How can i construct my class template in my member function newNode (in std=++98) without new operator ?
I tried to put an constructor of Node or the variable key but it doesn't work .

template <class T>
class Node{
public:

    Node(){
        _left = NULL;
        _right = NULL;
        _height = 0;
    };

    Node(const Node &ref);
    Node &operator=(const Node &ref);
    ~Node(){};

    T _key;
    Node *_left;
    Node *_right;
    int _height;
};


template <class T, class A = std::allocator<Node<T> > >
class Tree{
public:
[...]
//attribut 
Node<T> *head;
A _alloc;


  Node<T> *newNode(T key){
    Node<T> *node = _alloc.allocate(sizeof(Node<T>));
    _alloc.construct(node, ???);

    return (node);
  }
};

What can i put in my 2nd argument of construct ?


Solution 1:[1]

allocate() already calculates the memory required for objects, you shouldn't use sizeof there. Also, don't use construct(), it was removed in C++20. Use placement new instead:

  Node<T> *newNode(T key){
    Node<T> *node = _alloc.allocate(1); // allocate 1 * sizeof(Node<T>)
    new(node) Node<T>(/*arguments to Node<T> constructor, but Node<T> only has default constructor, so nothing goes here*/);

    return node;
  }

With C++20, you can also use std::construct_at(), which has easier syntax than placement new:

  Node<T> *newNode(T key){
    Node<T> *node = _alloc.allocate(1); // allocate 1 * sizeof(Node<T>)
    node = std::construct_at(node);

    return node;
  }

To use construct() before C++11, you need to create an object to be copied:

  Node<T> *newNode(T key){
    Node<T> *node = _alloc.allocate(1); // allocate 1 * sizeof(Node<T>)
    _alloc.construct(node, Node<T>());

    return node;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1