placement2.cpp
773 Bytes
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
#include <iostream>
#include <new>
#include <string>
using namespace std;
class Arena {
public:
virtual void* alloc(size_t s)
{
return malloc(s);
};
virtual void free(void* s)
{
::free(s);
};
};
class object {
public:
object()
{
throw 0;
}
};
void* operator new(size_t sz, Arena* a)
{
return a->alloc(sz);
}
void operator delete(void* s, Arena* a)
{
a->free(s);
cout << "operator delete called" << endl;
}
int main()
{
Arena a;
try {
string* s = new (&a) string("s");
object* o = new (&a) object;
s->~string();
o->~object();
a.free(s);
a.free(o);
}
catch (int) {
cout << "Exception of type int caught" << endl;
}
}