简体   繁体   English

使用由不同分配器分配的内存

[英]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: 现在,我构造一个类型为Uvector ,后来想使用移动语义,以便可以将其消耗的内存用于类型为Tvector ,如下所示:

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.

相关问题 我可以使用分配器对象来释放另一个分配器分配的内存吗? - Can I use an allocator object to free memory allocated by another allocator? 为什么使用 realloc 重新分配,使用 allocator::allocate 预先分配的 memory 保存旧的起始 memory 地址? - Why does reallocating with realloc, a pre-allocated memory using allocator::allocate conserve the old start memory address? 将内存池分配器耦合到托管已分配实例的各种内存池 - Coupling memory pool allocator to various memory pools hosting the allocated instances 存储在 memory 中的 shared_ptr 的删除器是否由自定义分配器分配? - Is a shared_ptr's deleter stored in memory allocated by the custom allocator? 将 Vulkan memory 分配器与 Volk 一起使用 - Using Vulkan memory allocator with Volk 我是否应该在使用多态分配器分配的 object 上调用“删除” - Should I call `delete` on object allocated using polymorphic allocator 释放在不同DLL中分配的内存 - Freeing memory allocated in a different DLL 使用 Std::allocator 在特定地址分配内存 - Using Std::allocator to alocate memory at specific adress C ++分配器在销毁/复制/移动时应如何处理其分配的内存? - How should a C++ allocator handle its allocated memory when it is destroyed/copied/moved? 管理使用新char *创建但使用自定义分配器分配给std :: vector元素的内存块 - Managing memory block created with new char* but allocated to std::vector elements with custom allocator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM