简体   繁体   中英

Using Memory Allocated by Different Allocator

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

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

Is it safe for me to use the memory allocated by u 's allocator in t 's move constructor, and later deallocate it using t 's allocator? If so, what would I have to do to ensure that this operation would be safe? I'm guessing that I should first call allocator.destroy() for each element of u 's internal array using u 's allocator.

Yes, that is one of the purposed designs of the STL, that memory allocated by one allocator can be deallocated by another. This is because they wanted to be able to swap elements between containers (such as with list::splice ) without having to do anything with their allocators. That is (one of the reasons) why you can't really have stateful allocators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM