#include <iostream>
#include <algorithm>
using namespace std;
template<class T>
class myPointer
{
public:
T* pT_;
int *refcount_;
public:
myPointer(): pT_(NULL), refcount_(NULL) {};
myPointer ( T* objP )
{
pT_ = objP;
refcount_ = new int(1);
}
myPointer( const myPointer& node )
{
pT_ = node.pT_;
refcount_ = node.refcount_;
*refcount_ = *refcount_ + 1;
}
myPointer & operator= ( const myPointer& node )
{
if( this != &node )
{
pT_ = node.pT_;
refcount_ = node.refcount_;
*refcount_ = *refcount_ + 1;
}
return *this;
}
~myPointer ()
{
if( refcount_ != NULL )
{
if ( *refcount_ == 1 )
{
delete pT_;
delete refcount_;
}
else
*refcount_ = *refcount_ - 1;
}
}
};
template < class T >
class List
{
struct Node
{
myPointer<T> p_;
Node* next_;
Node( const myPointer<T>& obj )
{
p_ = obj;
next_ = NULL;
}
};
Node *head_;
public:
List( const myPointer<T>& obj )
{
head_ = new Node ( obj );
}
void addToList( const myPointer<T>& obj )
{
Node * newHead = new Node( obj );
newHead->next_ = head_;
head_ = newHead;
}
void printList()
{
Node *p = head_;
while ( p != NULL )
{
cout<< *(p->p_.pT_) << endl;
p = p->next_;
}
}
~List()
{
Node * p = head_;
while ( p != NULL )
{
Node *paux = p->next_;
delete p;
p = paux;
}
}
};
int main(int argc, char* argv[])
{
{
myPointer<int> x1( new int(5) );
myPointer<int> x2( new int(7) );
List<int> myList( x1 );
myList.addToList( x2 );
myList.addToList( x2 );
myList.addToList( x1 );
List<int> mySecondList( x1 );
mySecondList.addToList( x1 );
mySecondList.addToList( x2 );
mySecondList.addToList( x2 );
myPointer<int> x3( new int(9) );
myList.addToList( x3 );
mySecondList.addToList( x3 );
myList.printList();
cout<<endl;
mySecondList.printList();
}
_CrtDumpMemoryLeaks();
}
well, this is what I did as fast as I could, maybe it still has bugs, but none that I could find right now

. For the test i made it has no leaks.
As you can see you have only three objects ( x1, x2, x3 ) that are shared among 2 lists.
More over, you can have the same object more times in the same list ( x1 and x2 appear twice in both lists ).
Insted of the device class you have a template parameter to the myPointer and List classes that will be the contained type. The test provided uses int as the template parameter.