// File: memory_management.cpp // Author: Chris Gill cdgill@cse.wustl.edu // Purpose: illustrates use of scope detector and copy-safe (reference counted) smart pointer #include "stdafx.h" #include #include #include using namespace std; #include "scope_detector.h" #include "safe_ref_counted_guard.h" // global scope detector object (See exercise 4 of the basic memory management studio) ScopeDetector global; // acquires ownership of a passed heap object through the passed (by value) auto_ptr void acquire_ownership (auto_ptr ap) { cout << "just entered acquire_ownership" << endl; cout << "about to leave acquire_ownership" << endl; } // acquires and passes back ownership of a heap object through by-value auto_ptrs auto_ptr return_ownership (auto_ptr ap) { cout << "just entered return_ownership" << endl; cout << "about to leave return_ownership" << endl; return ap; } int main (int, char *[]) { cout << "just entered main" << endl; // heap allocation of scope detector object and scope detector array // (See exercises 5 and 6 of the basic memory management studio) ScopeDetector * scope_detector_ptr = new ScopeDetector; ScopeDetector * scope_detector_array_ptr = new ScopeDetector[3]; // stack allocation of scope detector objects with default construction, copy // construction, and assignment (See exercise 3 of the basic memory management studio) ScopeDetector a; ScopeDetector b(a); ScopeDetector c; c = b; // heap deallocation of scope detector object and scope detector array // (See exercises 5 and 6 of the basic memory management studio) delete scope_detector_ptr; delete [] scope_detector_array_ptr; // local auto_ptr to a heap object (see exercise 3 of memory management idioms studio) auto_ptr ap(new ScopeDetector); // passing auto_ptr to a heap object into a function that takes ownership and // destroys the object (see exercise 4 of memory management idioms studio) auto_ptr ap1(new ScopeDetector); acquire_ownership (ap1); // passing auto_ptr to a heap object into a function that returns ownership back // to ap2 in main function (see exercise 4 of memory management idioms studio) auto_ptr ap2(new ScopeDetector); ap2 = return_ownership (ap2); // sharing of (heap) scope detector object by copy-safe reference counted guards SafeRefCountedGuard guard1; guard1.ptr(new ScopeDetector); SafeRefCountedGuard guard2(guard1); // copy construction SafeRefCountedGuard guard3; guard3 = guard1; // assignment // use of copy-safe reference counted guards within an STL vector vector v; SafeRefCountedGuard vector_guard; vector_guard.ptr(new ScopeDetector); v.push_back(vector_guard); vector_guard.ptr(new ScopeDetector); v.push_back(vector_guard); for (unsigned int i = 0; i < v.size(); ++i) { cout << "position " << i << " points to object at address " << v[i].ptr() << " which has value " << *(v[i].ptr()) << endl; } cout << "about to leave main" << endl; return 0; }