Smart pointers knowledge of C ++



We know that in addition to the static memory and stack memory, each program there is a pool of memory, this memory is called free space or heap. Program with dynamically allocated heap to store objects that is assigned to those objects at run time, when a dynamic object is no longer in use, our code must explicitly destroy them.

In C ++, the dynamic memory management by a pair of operator completion: new and delete, new: allocating a space for objects in dynamic memory and returns a pointer to the object pointer, delete: pointing a dynamic exclusive pointer , destroying objects and free the memory associated with it.

Dynamic memory management often there are two problems: one is to forget the release of memory, can cause a memory leak; one is the case where there are pointers that referenced memory is released it, it will produce a reference invalid memory pointer.

For easier (safer) to use dynamic memory, it introduces the concept of smart pointers. Smart pointers behaves like a conventional pointer, an important difference is that it is responsible for the automatic release of object points. Smart pointer difference between the two standard library that different methods of managing the underlying pointer, shared_ptr allow multiple pointers to the same object, unique_ptr the "exclusive" object points. The library also defines a class named weak_ptr along, which is a weak reference to an object managed by shared_ptr, three smart pointers are defined in the header file memory.



Why: For easier and safer to use dynamic memory , with smart pointers.

What it is: a smart pointer is responsible for the automatic release of the object pointed pointer.

There are four: shared_ptr, unique_ptr, weak_ptr, scoped_ptr. The first two important

Difference: shared_ptr allow multiple pointers to the same object, unique_ptr the "exclusive" object points.

how to use:

shared_ptr class

Statement, a null pointer default initialization:

shared_ptr < String> p1; // declaration stage can point to the type of 
shared_ptr <List < int >> P2;


The use of smart pointers and common pointers Similarly , a smart pointer dereference the returned object it points to an empty sentence before use

if(p1  && p1->empty())
    *p1 = "hi";


make_shared () function:
The safest use of dynamic memory allocation and methods is to call a standard library function named make_shared, this function allocates a dynamic objects in memory and initializes it returns a pointer to this object shared_ptr. Share_ptr header and the same, in the memory

shared_ptr<int> p = make_shared<int>(88);
shared_ptr<stringt> p1 = make_shared<string>(10, '9');


and assignment shared_ptr copy
when copying and assignment, will record the number of each shared_ptr shared_ptr other point to the same object.

We can think of each shared_ptr has an associated counter , commonly referred to as the reference count whenever we copy a shared_ptr, the counter is incremented . When we assign a new value to shared_ptr shared_ptr or destroyed (for example, a local shared_ptr goes out of scope), the counter will be decremented, once a shared_ptr counter to 0, it will automatically release objects they manage .

r = make_shared Auto < int > ( 42 is ); // r int is only one reference point by 
r = q; // to assign r, so that it points to a different address
     // objects pointed to increment the reference count q
     // decrement r reference point to the original object count
     // r points to the original object has no referrer, it will automatically release


shared_ptr managed objects automatically destroyed
when the last one to an object is destroyed shared_ptr, shared_ptr object class is automatically destroyed, it is through another special member functions - the complete destruction destructor, similar to the constructor, each class has a destructor. Destructor do operation control target destruction. Destructor typically used to release the allocated resource object. shared_ptr destructor decrements the object it points to a reference count. If the reference count goes to 0, shared_ptr destructor will destroy the object, and releases the memory occupied by it.


shared_ptr will automatically release the associated memory
when the dynamic object is no longer used, shared_ptr class will automatically release the moving object, this feature makes the use of dynamic memory becomes very easy. If you would shared_ptr stored in a container, then all the elements are no longer needed, but only part of it, just remember that those elements with erase delete no longer needed.





unique_ptr class

Unique_ptr a time, only one point to a given object, as a unique_ptr owns the object it points to, unique_ptr therefore does not support copying or ordinary assignment .


Although we can not copy or assignment unique_ptr, but can be reset by calling the release or transfer of ownership from a pointer (non-const) unique_ptr to another unique

// The transfer of ownership from p1 (point string Stegosaurus) to P2 
a unique_ptr < String > P2 (p1.release ()); // Release p1 is set to an empty 
a unique_ptr < String > P3 ( new new  String ( " Trex " ));
 // the transfer of ownership from p3 to p2 
p2.reset (p3.release ()); // the RESET release the original memory pointed to by p2


release members return unique_ptr currently saved and set to null pointer. Thus, p2 p1 is initialized to a previously saved pointer, p1 is set to null.

reset member to accept an optional pointer argument, so unique_ptr redirected given pointers.



How to answer interview questions about C ++ smart pointer?

1.   What is a smart pointer?

A: smart pointers (smart pointer) is a pointer to an object dynamically allocated memory (heap) of the class, for lifetime control, to ensure the correct object is automatically destroyed dynamically allocated, to prevent memory leaks (destructor is automatically invoked using the class to free memory). It is a common technique used to achieve reference count (in addition to exclusive resources, such as (the auto_ptr), only the reference, does not count (weak_ptr)). Smart pointer class counter with a point associated with the object class, the reference count how many objects to track the class share the same pointer . Each time a new object class to create, initialize the pointer and the reference count is set to 1 ; when the object is created as a copy of another object, with which corresponding reference copy constructor pointer and copy count increases; assign one object when the assignment operator reducing the reference count of the object referred to the left operand (if the reference count goes to zero, to delete an object), and increases the reference count of the right operand referents; destructor is invoked, constructor reduced reference count (If the reference count goes to zero, then delete the underlying objects).


2, why the principle use of smart pointers and smart pointers what is?

2, A: The reasons: (1): Manual malloc / new out of resources, is easy to forget free / delete;
                    (2): Local influence the flow of execution should be noted that the release of resources, easily lead to the return after resource leaks (such as free / delete ).
                    (3): midway throws an exception, not the release of resources. Such as: int * p1 = new int; int * p2 = new int [10000000]; delete p1; delele [] p2; because p2new memory is relatively large, if new fails, resulting in p1 never be released.

Principle: In order to solve (1), (2), (3) problems, create a resource out of time, to a class of objects to manage, at the end when the class object lifecycle, automatically calls the destructor frees resources . In addition, by operator overloading (overload and focusing * ->, etc.) may be used as the pointer.


3.   Analysis of the common smart pointers What?


(1) it is a class template C ++ standard library, auto_ptr objects by pointing to initialize dynamic memory created by new, it is the owner of this memory, a memory can not be distributed to the two owners ( exclusive resources ) . When the life cycle of an auto_ptr, its destructor will have an auto_ptr dynamic memory is automatically released.

(2) auto_ptr not pointing to the array, because auto_ptr destructor when only call delete, the array should be invoked delete []. (But uniquearray management is a contiguous space, it is copy-protected, the function is similar to the Vector.)

(3) auto_ptr can not be used as a container object, because it does not support the copy constructor and assignment (a mistake not easy to find), STL container elements often supports copy, assignment and other operations, auto_ptr will transfer ownership in the process, it will go wrong.



it is (C ++ 11 introduced, formerly known as scoped_ptr, scoped_ptr is the boost library), does not support the copy constructor and assignment, but better than auto_ptr, direct assignment will compile error (and auto_ptr biggest difference is within the class declared private copy constructor and assignment operator overloading, is for the shortcomings of the emergence of auto_ptr).


the shared_ptr

C ++. 11 or the boost shared_ptr, based on reference counting smart pointer. It can be freely assigned, until the memory reference count reaches zero this memory will be released. Cyclic chain structure formed may be a memory leak (circular references)


Circular reference questions (FAQ to oh)

In order to solve problems like this, C ++ 11 introduced weak_ptr, to break this circular reference.

the weak_ptr

C ++. 11 or the boost weak_ptr, weak references. One problem is that the reference count reference to each other to form a ring, and two pointer memory is not released. You need to manually break the circular reference or use weak_ptr. As the name suggests, the weak_ptr is a weak reference, which is a smart pointer for mating shared_ptr introduced, it points to a shared_ptr managed by an object without affecting the life cycle of referents, that is, it is only the reference does not count . If a memory is simultaneously references and shared_ptr weak_ptr, when all shared_ptr destructor, no matter there is no weak_ptr referenced memory, the memory will be released. So weak_ptr is no guarantee that it points to the memory must be effective, you need to check before using weak_ptr is empty pointer .

weak_ptr not overloaded operator-> operator * and operator, and therefore can not be used directly weak_ptr objects, calling its typical usage of the lock function is obtained shared_ptr example, further access to the original object.


How to determine whether the object weak_ptr failure?
1, expired (): Check the referenced object has been deleted.
2, lock () returns a pointer to shared, determining whether the pointer is NULL.
3, use_count () can be obtained by reference number shared, but slower.


Guess you like