placement new

代码直接在gcc里是可以编译通过的,在vc里编译,注意,如果是将例子代码加到MFC程序里,要注释掉源码中的DEBUG_NEW:

1
2
3
4
5
/*
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
*/

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Zone {
public:
	Zone()
	{}
	~Zone()
	{}
 
	void* New(size_t size)
	{
		// add your own allocating strategy here.
		return NULL;
	}
};
 
class ZoneObject {
public:
	void* operator new(size_t size, Zone* zone){ return zone->New(size); }
 
		void operator delete(void*, size_t) {}
	void operator delete(void* pointer, Zone* zone) {}
};
 
class Example0 : public ZoneObject {
public:
	Example0(int a0, const char *b0)
	{
	}
	~Example0()
	{
	}
};
 
class Example1 {
public:
	Example1(int a0, const char *b0)
	{
	}
	~Example1()
	{
	}
};
 
int main()
{
	Zone zone0;
	Zone *zone = &zone0;
	Example0 *example0 = new (zone)Example0(0, "hi");
	example0->~Example0();
	free(example0);
 
	Example1 *example1 = (Example1 *)malloc(sizeof(Example1));
	example1 = new (example1)Example1(0, "hi1");
	example1->~Example1();
	free(example1);
	return 1;
}