Reputation: 14827
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.
Upvotes: 4
Views: 162
Reputation: 75130
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.
Upvotes: 2