[英]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>.
假设我有一个称为
vector
的类,该类维护由std::allocator<T>.
分配的一些内部类型T
动态数组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: 现在,我构造一个类型为
U
的vector
,后来想使用移动语义,以便可以将其消耗的内存用于类型为T
的vector
,如下所示:
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? 对我来说,在
t
的move构造函数中使用u
的分配器分配的内存,然后再使用t
的分配器对其进行释放,是否安全? 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. 我猜想我应该首先使用
u
的分配器为u
内部数组的每个元素调用allocator.destroy()
。
Yes, that is one of the purposed designs of the STL, that memory allocated by one allocator can be deallocated by another. 是的,这是STL的目标设计之一,由一个分配器分配的内存可以由另一个分配器释放。 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. 这是因为他们希望能够在容器之间交换元素(例如,使用
list::splice
),而不必对其分配器做任何事情。 That is (one of the reasons) why you can't really have stateful allocators. 这就是(原因之一)为什么您不能真正拥有有状态的分配器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.