Using memory allocated with another allocator

Suppose I have a class called vector that supports some internal dynamic array of type T allocated by std::allocator<T>. . Now I am building a vector type U , and later I want to use move semantics so that I can use the memory it consumes for vector type T , for example:

 vector<unsigned> u(512); // Do something with v. vector<double> t = std::move(u); // Do something with t. // Later, t gets destroyed. 

Is it possible to use the memory allocated by the U allocator in the T move constructor, and then free it with the T allocator? If so, what should I do to ensure that this operation is safe? I assume that I should first call allocator.destroy() for each element of the internal array U , using U allocator.

+4
source share
1 answer

Yes, this is one of the designated STL constructs; this memory allocated by one allocator can be freed by another. This is due to the fact that they wanted to be able to change elements between containers (for example, with list::splice ) without doing anything with their distributors. That is (one of the reasons) why you cannot have full-fledged dispensers.

+2
source

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


All Articles