Resources: Useful and.
Resources: Memory, file descriptor, mutex, glyph and brush in graphical interface, database connection, socket
Class Investment {}; investment* createinvestment (); void F () {investment* PINV = createinvestment (); .... delete PINV;//IF in ... You cannot delete a pointer if you have return or throw an exception. ///This leads to the need to automatically delete instead of manual deletion, and therefore to manage resources within the object. And, of course, there are smart pointers auto_pte and shared_ptr.
Therefore, the resource must be placed in the object after it is obtained. RAII principle (initialization of resource acquisition)
Use the method of the previous article to prevent exceptions when destructors are used.
You cannot have auto_ptr point to the same object.
RCSP (reference-counting smart pointer) reference counting-type wisdom pointers
But tr1::shared_ptr cannot break the error of "being used," which is caused by the mutual reference.
Smart pointers can only do delete but not delete[], but dynamically allocated arrays can be implemented in string and vector.
In a word, the pointers are put into the object.
Mutex instance:
void Lock (mutex* pm); void unlock (mutex* pm); Class Lock {public:explicit lock (mutex* pm): mutexptr (PM) {lock (mutexptr);} ~lock () {unlock (mutexptr);} private:mutex* Mutexptr; Lock (const lock& s); Mutexes can avoid copying constructors. lock& operator= (const lock& s); };
The second method of avoiding unnecessary duplication:
void Lock (mutex* pm); void unlock (mutex* pm); Class Lock {public:explicit lock (mutex* pm): mutexptr (Pm,unlock) {lock (Mutexptr.get ());//mutex has a deletion that refers to a reference count of 0 o'clock to perform the steps. The reason for using get () is to provide the original pointer. ~lock () {unlock (mutexptr);} private:shared_ptr<mutex>mutexptr; Lock (const lock& s); Mutexes can avoid copying constructors. lock& operator= (const lock& s); };
Both Auto_ptr and shared_ptr provide the Get () function to provide the original pointer.
In general, explicit conversions are better than implicit conversions.
The purpose of RAII is to allow for a resource-friendly release.
Next, let's take a look at the delete and new
When new[], the array is dynamically allocated, including the size of the array, so that the delete knows how many calls.
Of course, the advent of the C + + standard library has reduced the need for arrays.
shared_ptr<a>pt;
A*a=new A; The type of new A is the original pointer type. And shared_ptr is the smart pointer type.
Just sort it out here. Next look at 4: Design and statement.