This chapter mainly refers to the knowledge of resource management, the most commonly used resources in C + + programs is the dynamic allocation of memory, but memory is only one of the many resources that must be managed, other common resources are file descriptors, mutexes, graphical interface fonts and brushes, database connections, and network sockets. No matter what kind of resource it is, it is important that you return it to the system when you no longer use it.
Clause 13
Investment* createInvestment(); //返回指针,指向Investment继承体系内的动态分配对象,调用者有责任删除它
It is common to call this factory function to release the PINV object at the appropriate time.
void f(){ Investment* pInv = createInvestment(); ... delete pInv;}
When a lot of unexpected situations cause PINV to fail to release, in order to ensure this, the resource needs to be put into the object, and when the control flow leaves F, the object's destructor will automatically release those resources (put the resources in the object, you can rely on C + + destructor to ensure that the resources are freed).
void f(){ std::auto_ptr<Investment> pInv(createInvestment()); ...}
The key to managing resources with objects:
(1) Immediately after obtaining the resources, put into the management object;
(2) Management objects use destructors to ensure that resources are released.
Auto_ptr will automatically destroy the object when it is destroyed, so be careful not to have multiple auto_ptr pointing at the same object at the same time. To prevent this, auto_ptrs has an unusual nature: if you copy them by using the copy constructor or the copy assignment operator, they become null, and the copied pointers get the unique ownership of the resource.
std::auto_ptr<Investment> pInv1(createInvestment());std::auto_ptr<Investment> pInv2(pInv1); // 现在pInv2指向对象,pIn1被设为nullpInv1 = pInv2; // 现在pInv1指向对象,pInv2被设为null
Resources managed by Auto_ptrs must have absolutely no more than one auto_ptr pointing at it at the same time, so that the STL container cannot store auto_ptr (the STL container requires its elements to perform the normal copy behavior).
And TR1 's tr1::shared_ptr is a RCSP:
void f(){ ... std::tr1::shared_ptr<Investment> pInv1(createInvestment()); std::tr1::shared_ptr<Investment> pInv2(pInv1); // pInv1和pInv2指向同一个对象 pInv1(pInv2); // 同理 pInv1 = pInv2; // 同理 ...}
So tr1::shared_ptrs can be used in the context of STL containers.
Both auto_ptr and tr1::shared_ptr do delete instead of delete[in their destructors, meaning that arrays that are dynamically allocated cannot be used. Generally for dynamically allocated arrays are vector and string, of course, using the Boost library, you can use Boost::scoped_array and Boost::shared_array.
Continuous update ...
Reading notes _effective c++_ resource Management