13. Managing Resources with objects
void f () { investment* PINV = Createinvestment (); ... Delete Pinv; }
- There is a problem with the above code: An exception occurred before the delete, causing the PINV to be deleted, causing a resource leak.
- Workaround: RAII Resource acquisition is initialization resource acquisition time is initialized
using smart pointers, the code is as follows:
void f () { auto_ptr<investment> pinv (Createinvestment ()); }
14. Beware of copying behavior in resource management classes
When a Raii object is copied, it is generally possible to select the following.
- Prohibit assignment
- Reference count for the underlying resource
- Replicating underlying resources
- Transferring ownership of underlying resources
Share_ptr allows you to specify a remove device
15. Provide access to the original resource in the resource management class
Auto_ptr,share_ptr provides a get function to get the original resource.
When customizing Raii, you can use both display and implicit conversions.
Implicit conversion: operator Fonthandle () const {return F;}
16. Use the same form when using new and delete in pairs
New Using Delete
New [] using delete []
The memory model of new [] may be: number of arrays + elements of each array. Non-paired use can cause undefined behavior.
Calling delete on new [] may cause other objects to be non-destructor.
typedef usage considerations, do not define arrays
17. Placing a Newed object into a smart pointer with a separate statement
int priority (); void Processwidget (shared_ptr<widget> pw, int priority); Processwidget (shrare_ptr<widget> (new Widget), priority ());
The above code issues are as follows:
possible order of execution is
Execute New Widget
Call priority
Call Share_ptr
if the priority call exception causes the new widget resource to be compromised.
here's how to fix it:
Share_ptr<widget> PW (new Widget);p rocesswidget (PW, priority);
Effective C + +--resource management