-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlazy-delete.cpp
More file actions
38 lines (34 loc) · 1.05 KB
/
lazy-delete.cpp
File metadata and controls
38 lines (34 loc) · 1.05 KB
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
//Author: Ugo Varetto
//Lazy delete:
//first call to delete invokes destructor and
//replaces instance with "DeletedType" instance
//second call to delete actually frees allocated memory
//useful in cases where you have multiple references to an
//object and want to implement a garbage-collection step
//to remove all the references pointing to empty objects
#include <cassert>
#include <iostream>
// derive from Deleted/Empty/Deletable Type
struct DeletedType {
virtual bool Empty() const { return true; }
virtual ~DeletedType() { std::cout << "~DeletedType\n";}
};
struct Type : DeletedType {
virtual bool Empty() const { return false; }
void operator delete(void* p) {
std::cout << "Type::operator delete\n";
new (p) DeletedType;
}
~Type() { std::cout << "~Type\n"; }
};
int main(int, char**) {
DeletedType* t = new Type;
DeletedType& r = *t;
assert(not r.Empty());
//replace instance with a DeletedType instance
delete t;
assert(r.Empty());
//physically free memory
delete t;
return 0;
}