Manage resources with objects
Resources are automatically released through automatic calls of object destructor
Part 1: typical examples of Object-based resource management
1. STL: auto_ptr
Put the resource management object immediately after obtaining the resource
std::auto_ptr
pInv(createInvestment());
Resources are automatically released when the lifecycle of pInv expires.
Note: auto_ptr has a strange nature: there will not be multiple auto_ptr pointing to the same resource at the same time.
Std: auto_ptr
PInv2 (pInv); // pInv2 points to the object, pInv is set to nullpInv = pInv2; // pInv points to the object, and pInv2 is null
Auto_ptr when copying or assigning values,
Transfer ownership of bottom Resources
2. RCSP (reference counting smart pointer)
Continuously track the total number of objects pointing to a resource and automatically release the resource when no one points to it .. Similar to Java's garbage collection mechanism.
E.g. TR1: shared_ptr
The following is a simple Reference counting smart pointer.
// copyright @ L.J.SHOU Dec.23, 2013// class for managing pointer, smart pointer class#ifndef HAS_PTR_H_#define HAS_PTR_H_#include
class HasPtr;class U_Ptr{ friend class HasPtr; int *ip; size_t use; U_Ptr(int *p): ip(p), use(1) { } ~U_Ptr() { delete ip; }};class HasPtr{public: HasPtr(int *p, int i) : ptr(new U_Ptr(p)), val(i) {} // copy members and increment the use count HasPtr(const HasPtr &rhs): ptr(rhs.ptr), val(rhs.val) { ++ ptr->use; } HasPtr& operator=(const HasPtr &rhs); // if use count goes to zero, delete the U_Ptr object ~HasPtr() { if(--ptr->use == 0) delete ptr; } int *get_ptr() const { return ptr->ip; } int get_int() const { return val; } void set_ptr(int *p) { ptr->ip = p; } void set_int(int i) { val = i; } int get_ptr_val() const { return *ptr->ip; } int set_ptr_val(int i) { *ptr->ip = i; }private: U_Ptr * ptr; // pointer to use-counted U_Ptr class int val;};// increment rhs's use count first to avoid self assignmentHasPtr& HasPtr::operator=(const HasPtr &rhs){ ++ rhs.ptr->use; // increment use count on rhs first if(--ptr->use == 0) delete ptr; // if use count goes to zero, delete object ptr = rhs.ptr; val = rhs.val; return *this;}#endif
Part 2: how to copy Resource Management Objects
In C ++, the copy constructor and copy assignment of the class are used to control the replication of resource objects.
There are usually four policies:
1. Prohibit replication: declare copy constructor and copy assignment as private and will not be implemented.
2. reference counting method: When a value is assigned, the number of referenced resources increases by 1. For example, shared_ptr
3. Copy bottom resources: each object has its own resources and cannot share resources.
4. transfer the ownership of the bottom Resource: e.g. std: auto_ptr