[ create a new paste ] login | about

Link: http://codepad.org/IxVgO4NE    [ raw code | output | fork ]

C++, pasted on Feb 4:
#include <algorithm>
#include <iostream>
#include <vector>

class iref{
public:
	iref():count(1) { }
	virtual ~iref(){ count = 0; }

	virtual void release() { --count; if(!count)delete this; }  
	virtual void add()     { ++count; }
	//.......

	static void *operator new(size_t size)
	{ 
		void *rhs = ::operator new(size);
		vec.push_back(static_cast<iref*>(rhs));
		return rhs;
	}

	

	static void clear_all(){
		for(std::vector<iref*>::iterator i = vec.begin(); 
			i != vec.end(); 
			++i)
			(*i)->iref::release();
		vec.clear();
	}
protected:
	int count;
	static std::vector<iref*> vec;
};

std::vector<iref*> iref::vec;

class a: public iref{
public:
	a(): iref()	{ std::cout << "a(): iref()"  << std::endl; }
	virtual ~a(){ std::cout << "~a(): iref()" << std::endl; }

	virtual void release() {
		--count; 
		if(!count){
			vec.erase(std::find(vec.begin(), vec.end(), this));
			delete this;
		}  
	}
};

class b: public iref{
public:
	b(): iref()	{ std::cout << "b(): iref()"  << std::endl; }
	virtual ~b(){ std::cout << "~b(): iref()" << std::endl; }

	virtual void release() {
		--count; 
		if(!count){
			vec.erase(std::find(vec.begin(), vec.end(), this));
			delete this;
		}  
	}
};

int main(){
	std::vector<iref*> v;

	a *a1 = new a;
	a *a2 = new a;
	a *a3 = new a;
	b *b1 = new b;

	b st1;
	a st2;

	b1->release();
	a1->release();

	iref::clear_all();

	return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
a(): iref()
a(): iref()
a(): iref()
b(): iref()
b(): iref()
a(): iref()
~b(): iref()
~a(): iref()
~a(): iref()
~a(): iref()
~a(): iref()
~b(): iref()


Create a new paste based on this one


Comments: