This article introduces four smart pointers of c ++, the last three of which are newly added in c ++ 11, and auto _ ptr has been discarded.
To compile c ++ 11, you must install g ++-4.8.
Sudo add-apt-repository ppa: ubuntu-toolchain-r/test
Sudo apt-get update
Sudo apt-get instal gcc-4.8
Sudo apt-get install g ++-4.8
Specify the standard during compilation:
G ++-4.8-std = c ++ 11
Auto_ptrFor details, refer to here
Auto_ptr is the first smart pointer added to the c ++ standard to promote RAII. It implements the most basic resource management, but unlike other types, auto_ptr has no replication semantics. It implements the mobile semantics during replication. When copying and assigning auto_ptr values, the ownership of the managed resources is changed by default. For this reason, it cannot be used in stl containers either, because the elements in the containers must support replicability and assignment. Another factor limiting its use scope is that its destructor calls delete by default and cannot be overloaded. Therefore, it cannot support objects such as arrays.
~ getvalue(){ <A> ptr1( A(<A> ptr2( A(->getvalue()==->getvalue()=== ()==NULL);
Unique_ptrFor details, refer to here
Due to various problems in auto_ptr, in c ++ 11, unique_ptr is replaced by auto_ptr. They do basically the same thing, but unique_ptr does not support replication semantics and only supports mobile semantics, therefore, you cannot perform common copy or value assignment operations (except when the unique_ptr to be destroyed is returned), but you can assign values to the mobile structure. To put it bluntly, you need to display the move operation when copying. In addition, unique_ptr can be used to reload the deleteer so that it supports arrays and other types.
unique_ptr<A> ptr1( A(<A> ptr2( A(= ptr2; ptr1 = move(ptr2); assert(ptr2==<A[]> ptr3( A[]{,}); assert(ptr3[].getvalue()==].getvalue()==);
For details, refer to here
Generally, the smart pointer refers to shared_ptr, which allows sharing resources and using reference counting to record resources to be shared by several pointers. When release () is called, the reference count of the previously managed resource is reduced by 1 when the Destructor or the value is copied and assigned, and the resource is released when the count is 0.
shared_ptr<A> ptr1( A(<A> ptr2( A(->getvalue()====->getvalue()=========->getvalue()==->getvalue()==);
For details, refer to here
When shared instances are used for mutual reference, resources cannot be released, for example:
<B>~<<<A>~<<<B> pb(<A> pa(->pa_value =->pb_value =====)
Reference:
After modification, pb-> pa_value = pa will not increase the Count of pa. pa count is 1. After leaving the scope, the count is 0, and pa is released normally. Therefore, pb count will be reduced to 0, release normally.