Don ' t use the get to initialize or assign another smart pointer.
The code that has the return from get can not delete the pointer
Although the compiler would not complain, it's an error to build another smart pointer to the pointer returned by get
shared_ptr<int > P (new int (42 )); // reference count is 1 int *q = P.get (); // OK; but does not delete the its pointer {shared_ptr < (q);} // block ends. Q is destroyed, and the Memory to which Q points is freed int f = *p; // undefined. The memory to which P points is freed.
Using our Own deletion Code
void end_connection (connection *p) { disconnection (*p);} void F (destination &D) { = conn (&D); shared_ptr<connection P (&C, end_connection); // Use the connection // When f exists, even if by an exception, the connection resourcewould be properly closed}
For Unique_ptr
Call Release () breaks the connection between a unique_ptr and the object it had been managing. Ofter the pointer returned by release () are used to initialized or assign another pointer
unique_ptr<int> P2 (newint);p 2.release (); // wrong! P2 the memory, and we have lose the pointerauto P = p2.release (); // OK, but we must remember to delete p
Backward compatibilities auto_ptr
Although Auto_ptr is still part of the library, programs should use UNIQUE_PTR instead.
C + + Dynamic Memory (Part 2)