Skip to content

Instantly share code, notes, and snippets.

@bastih
Forked from grundprinzip/gist:1059800
Created July 2, 2011 07:30
Show Gist options
  • Save bastih/1059822 to your computer and use it in GitHub Desktop.
Save bastih/1059822 to your computer and use it in GitHub Desktop.
#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