How to use C++ Smart pointer shared_ptr
This article introduces the knowledge of "how to use C++ smart pointer shared_ptr". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. What is shared_ptr?
A variety of pointers in clocking 11, including shared_ptr, are template types, meaning that the user can specify the type of action he wants.
You can create a shared_ptr as follows:
What operations are supported by shared_ptrp1; / / p1=NULL2 and shared_ptr?
Create: shared_ptr p = make_shared
Determine whether it is NULL:if (p)
Get the pointing object
Wait
3. How to create an instance of shared_ptr?
Dynamically apply for object memory through the make_shared () function in C++ 's standard library, and return the shared_ptr of this object:
Shared_ptrp1; p1 = make_shared; 4. What is the reference count of shared_ptr? How do I view it?
Because it allows multiple shared_ptr to point to the same object, C++ supports "reference counting", that is, counting how many shared_ptr points to the same object. When the shared_ptr of an object increases, the reference count increases by one; when the shared_ptr of an object decreases, the reference count decreases by one.
The function member of the use_count of the shared_ptr object returns the reference count value:
Shared_ptrp2, p3positionp2 = p1utterp3 = p1scarp / p1nominep2menp3 points to the same object, so the referenced technical value is 3cout.