问题描述
大家好,
我正在编写一个内存池应用程序,但遇到以下问题:
当我开始时,应用程序正在分配(通过使用malloc)大量的内存.然后,一个char指针列表指向分配的内存的不同位置.当我调用分配时,将返回这些指针之一.
问题是,当我调用deallocate时,我只想显式地调用对象的析构函数,然后使内存块再次可用.换句话说,我不想释放内存.
所以我的解除分配看起来像这样:
Hello people,
I am writing a memory pool application and I have the below problem:
When I start, the application is allocating (by using malloc) a big amount of memory. Then, a list of char pointers point to different places of the allocated memory. When I call allocate, one of these pointers is returned.
The problem is, when I call deallocate, I only want to explicitly call the destructor of the object and then make the memory block available again. In other words, I do not want to free the memory.
So my deallocate looks like that:
void Pool:: Deallocate(void* pObj)
{
.. Call object destructor here ..
m_ListOfSlices.push_back((char*)pObj);
m_AllocLeft += 1;
}
如何调用pObj
指向的对象的析构函数?
请记住,我真的不需要模板解决方案.
由于操作员删除,必须有一种方法实际上是在做同样的事情!我尝试调试运算符delete,但是我没有运气.
请帮忙!
修改后的:::
非常感谢您的回答,
要回答答案1,恐怕您实际上可以做到.您实际上可以执行pMem->~A();
,然后调用delete pMem;
要回答问题2,我很早以前就读过parashift教程,问题是它们根本不适用于我的情况;).我正在尝试做另一件事.不过,非常感谢您的答复:)
How can I call the destructor of the object that pObj
points to?
Keep in mind that I do not really want a template solution.
There must be a way, since operator delete, is actually doing the same thing! I tried to debug the operator delete, but I had no luck.
Please help!
Revised:::
Thanks very much for your answers,
To answer answer 1, I am afraid you can actually do that. You can actually do pMem->~A();
and then call delete pMem;
To question answer2, I have read the parashift tutorials long ago, the problem is that they do not apply to my situation at all ;) . I am trying to do a different thing. Thanks very much for the reply though :)
推荐答案
A* pA;
pA = (A*)new char[sizeof(A)];
new(pA)A(...);
pA->~A();
delete[] (char*)pA; pA = 0;
pA = new A(...);
delete pA; pA = 0;
这篇关于如何销毁对象,但不能释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!