您的位置:首页 > 其它

如何在指定的内存区域 new 一个对象

2009-10-24 09:32 323 查看
#include "stdafx.h"

#include "iostream.h"

class A

{

public:

A() {cout<<"A()"<<endl;}

~A() {cout<<"~A()"<<endl;}

void* operator new (size_t size,void* pBuffer)

{

cout<<"A::new"<<endl;

return pBuffer;

}

void A1() {cout<<"A1()"<<endl;}

};

int main(void)

{

char pBuffer[1024];

A* a=new (pBuffer) A;

a->A1();

a->~A();

return 0;

}

运行结果

A::new

A()

A1()

~A()

这才正确,呵呵,前面写错了点,不好意思

这个程序编译有一个报警

warning C4291: 'void *__cdecl A::operator new(unsigned
int,void *)' : no matching operator delete found;
memory will not be freed if initialization throws an
exception

C:/VCWork/memObjTest/memObjTest.cpp(12) : see declaration of 'new'

说的是没有与异型new对应的delete,不要去管他就是了,因为这种调用法,最重要的就是不能用delete清除对象,否则,内存指针在对象清除时就被清除了,而推出函数时,自动释放pBuffer时,因为这块内存已经标记清除,肯定出错

很多C++的书籍说,显式调用析构函数是一个高级话题,说的就是这种情况
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: