STL Vector默认使用'new'和'delete'用于内存分配? [英] Does STL Vector use 'new' and 'delete' for memory allocation by default?
问题描述
我正在开发一个应用程序的插件,其中内存应该由应用程序分配并跟踪它。因此,应当以缓冲器的形式从主机应用程序获得存储器句柄,并且稍后将它们返回给应用程序。现在,我正在计划使用STL向量,我想知道它在内部使用什么样的内存分配。
I am working on a plugin for an application, where the memory should be allocated by the Application and keep track of it. Hence, memory handles should be obtained from the host application in the form of buffers and later on give them back to the application. Now, I am planning on using STL Vectors and I am wondering what sort of memory allocation does it use internally.
它在内部使用'new'和'delete' ?如果是,我可以重载'新'和'删除'与我自己的功能?或者,我应该创建自己的模板分配器,这对我来说是一个困难的工作,因为我没有经验的创建自定义模板。
Does it use 'new' and 'delete' functions internally? If so, can I just overload 'new' and 'delete' with my own functions? Or should I create my own template allocator which looks like a difficult job for me since I am not that experienced in creating custom templates.
欢迎任何建议/示例代码。内存句柄可以从这样的应用程序获得
Any suggestions/sample code are welcome. Memory handles can be obtained from the application like this
void* bufferH = NULL;
bufferH = MemReg()->New_Mem_Handle(size_of_buffer);
MemReg()->Dispose_Mem_Handle(bufferH); //Dispose it
推荐答案
默认使用 std :: allocator
,并且需要使用 std :: allocator
全局运算符new(即 :: operator new(size_t)
)来获取内存(20.4.1.1)。但是,不需要在每次调用 allocator :: allocate
时调用一次。
vector
uses std::allocator
by default, and std::allocator
is required to use global operator new (that is, ::operator new(size_t)
) to obtain the memory (20.4.1.1). However, it isn't required to call it exactly once per call to allocator::allocate
.
,如果你替换全局运算符new然后向量
将使用它,虽然不一定在某种程度上真正允许你的实现管理内存高效。任何你想使用的特殊技巧原则上可以通过 std :: allocator
完全不相关,以10MB的块和子分配抓取内存。
So yes, if you replace global operator new then vector
will use it, although not necessarily in a way that really allows your implementation to manage memory "efficiently". Any special tricks you want to use could, in principle, be made completely irrelevant by std::allocator
grabbing memory in 10MB chunks and sub-allocating.
如果你有一个特定的实现,你可以看看它的向量
的行为,这可能是足够好,如果你的计划分配策略本质上是平台特定的。
If you have a particular implementation in mind, you can look at how its vector
behaves, which is probably good enough if your planned allocation strategy is inherently platform-specific.
这篇关于STL Vector默认使用'new'和'delete'用于内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!