Using Allocator in C ++ (STL Tree)

I recently tried to understand how C ++ distributors work, and I was looking for a red-black tree implementation that the STL library uses for things like std::setor std::map, but there are some things that I can’t lower my head to.

The first thing to do is convert the dispenser from the type the container should store - _Val- into the node type that the tree uses - _Rb_tree_node<_Val>- using the re-binding pattern:

typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template
    rebind<_Rb_tree_node<_Val> >::other _Node_allocator;

typedef __gnu_cxx::__alloc_traits<_Node_allocator> _Alloc_traits;

I can figure it out.

Now that the element is inserted and it needs to create a new node, it does this

_Node_type __node = _Alloc_traits::allocate(_M_get_Node_allocator(), 1);

which I assume allocates space for one node. But then it does

::new(__node) _Rb_tree_node<_Val>;

, , __node .

_Alloc_traits::construct(_M_get_Node_allocator(), __node->_M_valptr(), ...);

, node ( node), __node->_M_valptr(), _Val*.

- , .

+4
3
::new(__node) _Rb_tree_node<_Val>;

" ". , , . __node node, _Rb_tree_node<_Val> .

_Alloc_traits::construct(_M_get_Node_allocator(), __node->_M_valptr(), ...);

_Val , __node->_M_valptr().

+6

::new(__node) _Rb_tree_node<_Val>;

new, _Rb_tree_node<_Val> __node). node.

- _M_valptr().

_Alloc_traits::construct(_M_get_Node_allocator(), __node->_M_valptr(), ...);

( ) allocator construct, new ( ). , , . value.

+2

-, "" ", , .

void * mem = malloc(sizeof(MyStruct));
MyStruct * my_struct_ptr = new(mem) MyStruct(/*Args...*/);

/*Do stuff...*/

my_struct_ptr->~MyStruct();//Literally one of the only times a good programmer would ever do this!
free(mem);

:

char * mem = new char[sizeof(MyStruct)];
MyStruct * my_struct_ptr = new(mem) MyStruct(/*Args...*/);

/*Do stuff...*/

my_struct_ptr->~MyStruct();//Literally one of the only times a good programmer would ever do this!
delete mem;

:

char mem[sizeof(MyStruct)];
MyStruct * my_struct_ptr = new(mem) MyStruct(/*Args...*/);

/*Do stuff...*/

my_struct_ptr->~MyStruct();//Literally one of the only times a good programmer would ever do this!

, , . EXCEPT , .

+2

Source: https://habr.com/ru/post/1651594/


All Articles