找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3779|回复: 1

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

[复制链接]
发表于 2007-12-11 22:32:57 | 显示全部楼层 |阅读模式
  1. typedef ACE_Allocator_Adapter<ACE_Malloc<ACE_LOCAL_MEMORY_POOL,ACE_SYNCH_MUTEX> > Malloc_Allocator;
  2. Malloc_Allocator gAlloc;
  3. class aaa
  4. {
  5. public:
  6. aaa(){printf("aaa\n");}
  7. ~aaa(){printf("~aaa() \n");}
  8. int x;
  9. };
  10. void *p = gAlloc.malloc(sizeof(aaa));
  11. aaa *poa = new (p) aaa(); //调用类aaa的构造函数
复制代码
。。。
释放:
gAlloc.free(poa);  //不能调用到poa的虚构函数
poa = NULL;
请问我释放空间用aAlloc.free(poa);还是delete poa;?
 楼主| 发表于 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[100];

    aaaa *b=new(t) aaaa;

    b->~aaaa();

    delete[] t;

    return 0;

}


输出如下:

bbbb(void)

aaaa(void)

~aaaa(void)

~bbbb(void)
您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-11-23 15:28 , Processed in 0.024959 second(s), 6 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表