-
-
Save bastih/1059822 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class A | |
{ | |
protected: | |
public: | |
int count; | |
A() : count(1) { }; | |
void retain() { ++count; } | |
void release() { if (--count == 0) { delete this; } } | |
virtual ~A() { } | |
void operator delete(void* ptr, size_t s) { | |
A* a = (A *) ptr; | |
if (a->count > 1) { | |
cout << "Attempt to delete object with retaincount > 1" << endl; | |
abort(); | |
} else { | |
::operator delete(ptr); | |
} | |
}; | |
}; | |
class B : public A | |
{ | |
public: | |
virtual ~B() { } | |
}; | |
template<typename T> | |
class C : public B | |
{ | |
public: | |
void * operator new(size_t s) { | |
return (void *) malloc(s); | |
} | |
void operator delete(void* ptr, size_t s) { | |
A* a = (A *) ptr; | |
if (a->count > 1) { | |
cout << "Attempt to delete object with retaincount > 1" << endl; | |
abort(); | |
} else { | |
free(ptr); /*i.e. strategy*/ | |
} | |
} | |
virtual ~C() { /* this could clean up resources! */ } | |
}; | |
int main() | |
{ | |
/* DO IT LIKE THIS */ | |
A* b = new C<int>; | |
b->release(); | |
/* Or like this */ | |
A* c = new C<int>; | |
delete c; | |
/* Should work for B too */ | |
A* e = new B; | |
delete e; | |
/* But never like this */ | |
cout << "Fail here" << endl; | |
A* d = new C<int>; | |
d->retain(); | |
delete d; | |
cout << " here too" << endl; | |
B* f = new B; | |
f->retain(); | |
delete f; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment