// Phil Ottewell's STL Course - http://www.pottsoft.com/home/stl/stl.htmlx // // RefCount supp. example © Phil Ottewell 1997 // // Purpose: // Shows how copy assignment and copy constructors work with containers #include #include #ifdef _WIN32 using namespace std; #endif class MyClass { public: MyClass() { piRefcount = new int; *piRefcount = 1; cout << "MyClass Constructor. Refcount = " << dec << *piRefcount << " for pointer " << hex << piRefcount << " this = " << this << endl; } // Copy constructor MyClass( const MyClass &mc ) { // Don't use the Copy Assignment in here ! this->piRefcount = mc.piRefcount; ++*piRefcount; cout << "MyClass Copy Constructor. Refcount = " << dec << *piRefcount << " pointer " << hex << piRefcount << " this = " << this << endl; } // Copy assignment MyClass & operator =( const MyClass &mcRHS ) { // Avoid self-assignment if ( this != &mcRHS ) { cout << "MyClass Copy Assignment. Refcount = " << dec << *piRefcount << " before re-assignment for pointer " << hex << piRefcount << " this = " << this << endl; if ( 0 == --*piRefcount ) { // If noone else is referencing current value of LHS before // assignment it can safely be destroyed cout << "MyClass Copy Assignment. deleted pointer" << endl; delete piRefcount; } // Copy RHS top LHS this->piRefcount = mcRHS.piRefcount; // Increase reference count ++*piRefcount; } cout << "MyClass Copy Assignment. Refcount = " << dec << *piRefcount << " pointer " << hex << piRefcount << " this = " << this << endl; return( *this ); } ~MyClass() { if ( piRefcount ) { if ( 0 == --*piRefcount ) { // Can destroy object's sub parts if no more references delete piRefcount; piRefcount = NULL; cout << "MyClass Destructor. Deleted " << "pointer data for pointer " << hex << piRefcount << " this = " << this << " because it had 0 references" << endl; } else { cout << "MyClass Destructor. Refcount = " << dec << *piRefcount << " pointer " << hex << piRefcount << " this = " << this << " after decr." << endl; } } else { cout << "MyClass Destructor. " << "Pointer data already deleted for pointer @ " << hex << piRefcount << " this = " << this << endl; } } private: int *piRefcount; }; int main() { int j; MyClass myTemp; vector v; vector::iterator iv; // initialize the vector with values cout << "Add some myTemps to vector ..." << endl; for ( j = 0; j < 3; j++) { v.push_back( myTemp ); } cout << "Erase myTemps from vector ..." << endl; while ( ( iv = v.begin() ) != v.end() ) { v.erase( iv++ ); } cout << "End of program - destructors should come soon ..." << endl; return 0; }