peakzhang 发表于 2007-12-11 22:32:57

使用内存池时,怎么调用对象的虚构函数?


typedef ACE_Allocator_Adapter<ACE_Malloc<ACE_LOCAL_MEMORY_POOL,ACE_SYNCH_MUTEX> > Malloc_Allocator;
Malloc_Allocator gAlloc;
class aaa
{
public:
aaa(){printf("aaa\n");}
~aaa(){printf("~aaa() \n");}
int x;
};
void *p = gAlloc.malloc(sizeof(aaa));
aaa *poa = new (p) aaa(); //调用类aaa的构造函数

。。。
释放:
gAlloc.free(poa);//不能调用到poa的虚构函数
poa = NULL;
请问我释放空间用aAlloc.free(poa);还是delete poa;?

peakzhang 发表于 2007-12-11 22:33:18

应该按自己调用析构的:

#include <iostream>
class bbbb
{
public:
    bbbb(void){std::cout<<"bbbb(void)\n";}
    ~bbbb(void){std::cout<<"~bbbb(void)\n";}
};

class aaaa :public bbbb
{
public:
    aaaa(void):i(0){std::cout<<"aaaa(void)\n";}
    ~aaaa(void){std::cout<<"~aaaa(void)\n";}
protected:
private:
    int i;
};


int

main (int argc, char *argv[])

{

    int *t =new int;

    aaaa *b=new(t) aaaa;

    b->~aaaa();

    delete[] t;

    return 0;

}


输出如下:

bbbb(void)

aaaa(void)

~aaaa(void)

~bbbb(void)
页: [1]
查看完整版本: 使用内存池时,怎么调用对象的虚构函数?