//1. The standard library provides two kinds of smart pointer types to manage dynamic objects, all defined in the header file memory, declared in the Std namespace. //shared_ptr: Allows multiple pointers to point to the same object. //Unique_ptr: The object that the exclusive refers to. //The standard library also defines the adjoint class of weak_ptr, which is a weak effect. Points to the objects managed by the shared_ptr. //operations supported by 2.shared_ptr and Unique_ptr:Shared_ptr<t>spunique_ptr<T>up: An empty smart pointer to an object of type T P: use p as a judging condition and true if p points to an object*p, p->Men : Get P pointing to the object p.Get(): Returns the pointer saved in P. Swap (p, q) p.swap (q): Exchange pointers for P and Q//3.shared_ptr Exclusive operation:Make_shared<t>(args): Returns a shared_ptr that points to an object that is dynamically assigned a type of T. Initialize this object with args. is the safe way to allocate and use dynamic memory. It is also a template itself. shared_ptr<T>p (q):p is a copy of Q, this operation increments the counter of Q, the pointer in Q must be able to be converted to T. P=Q:p and q are shared_ptr,p pointers that must be able to point to the object referred to by Q, which decrements the reference count of P and increments the reference count of Q. When P's reference count becomes 0, its managed memory is freed. shared_ptr<Const int> PInt (New int(Ten)); shared_ptr<int>PInt1; PInt1= PInt;//ErrorPInt = PInt1;//correctp.unique (): Returns True if the reference count of P is 1, otherwise returns Falsep.use_count (): May be slow, primarily for debugging, returns the number of smart pointers to shared objects with P//4. When shared_ptr is used in the container, when not all elements in the container are needed, remember to use erase to delete the elements that are not required. //5.new and Delete:1The memory allocated in free space is nameless, so new cannot name its assigned object, but instead returns a pointer to that object. 2. By default, dynamically allocated objects are initialized by default. 3You can use direct initialization or value initialization by using (). Direct initialization:int*pvalue =New int(Ten); Value initialization:int*pvalue =New int();4The Bad_alloc exception is thrown by default when new fails. Use location new to avoid throwing exceptions:int*pvalue =New(nothrow)intwhen allocating memory fails, pvalue will be a null pointer. Nothrow is defined in the header file new, declared in the namespace Std. 5the pointer passed to the delete must be a dynamically assigned pointer or a null pointer. The behavior of releasing the same pointer multiple times is undefined. 6When a delete is used, it is best to empty the pointer being manipulated. //6. You can initialize the shared_ptr directly with the pointer returned by new, which is explicit, so it can only be initialized directly.
C++primer 12th Chapter