Smart pointer shared_ptr [lockless Design Based on GCC]

Source: Internet
Author: User
ArticleDirectory
    • 1. shared_ptr Introduction
    • 2. shared_ptr Construction
    • 3. shared_ptr obtains the reference count or original pointer.
    • 4. Reduce reference count
    • 5. shared_ptr destructor
    • 6. Use shared_ptr like the original pointer
    • 7. Implement lock free reference count
1. shared_ptr Introduction

If boost is used, you will be very impressed with shared_ptr. Multiple shared_ptr points to the same object. Each shared_ptr adds the reference count of the object to + 1. When the reference count is 0,

The object will be destructed. This article implements a concise version of shared_ptr, which does not have many cross-platform features.CodeYou can run it on GCC again.

The reference count in this article is implemented by the ref_count_t class. See the detailed analysis below.

For details, see:

For the code, see: http://ffown.sinaapp.com /? P = 49

SVN Co http://ffown.googlecode.com/svn/trunk/fflib/lib

2. shared_ptr Construction

We expect the behavior of shared_ptr to be as close as possible to the behavior of the original pointer. Therefore, shared_ptr should support three constructor methods.

A. the empty structure is similar to void * P = NULL;

B. shared_ptr can be constructed through the original object pointer, similar to void * P = Q;

C. shared_ptr can be constructed through an existing shared_ptr.

First, shared_ptr is a template Class, which consists of connected attributes.

 
Private:
Object_t * m_dest_ptr;
Ref_count_t * m_ref_count;
};

M_dest_ptr points to the target object, and m_ref_count records the reference count of the object. For simplicity, the shared_ptr class follows the principle that m_dest_ptr and m_ref_count are both null or not null.

Here, object_t is the alias of the template type.

 
Template <typename T>
ClassShared_ptr_t
{
Public:
Typedef t object_t;
Typedef shared_ptr_t <t> self_type_t;

1> the target object and reference count are empty by default.

Template <typename T>
Shared_ptr_t <t>: shared_ptr_t (object_t * P ):
M_dest_ptr (P ),
M_ref_count (null)
{
If(Null! = M_dest_ptr)
{
M_ref_count =NewRef_count_t ();
}
}

Pai_ptr_t <int> P;

2> support for the original object pointer as the constructor Parameter

 
Template <typename T>
Shared_ptr_t <t>: shared_ptr_t (object_t * P ):
M_dest_ptr (P ),
M_ref_count (null)
{
If(Null! = M_dest_ptr)
{
M_ref_count =NewRef_count_t ();
}
}

Use Case: pai_ptr_t <int> P (New int ());

3> construct with existing shared_ptr

Template <typename T>
Shared_ptr_t <t>: shared_ptr_t (self_type_t & P ):
M_dest_ptr (P.Get()),
M_ref_count (P. ger_ref_count ())
{
If(Null! = M_dest_ptr)
{
M_ref_count-> Inc ();
}
}

Use Case: pai_ptr_t <int> q (P );

3. shared_ptr obtains the reference count or original pointer.

Sometimes you need to know the value of shared_ptr's current reference count. You can use shared_ptr to obtain the original pointer. So:

 
Size_t ref_count ()Const{ReturnM_ref_count! = NULL? (Size_t) m_ref_count-> size ():0;}
 
Object_t * Get () const {return m_dest_ptr ;}

So it is easy to verify the behavior of shared_ptr:

Shared_ptr_t P (New Int());
Assert (P. ref_count () =1);
Shared_ptr_t <Int> Q (P );
Assert (Q. ref_count () =1);
4. Reduce reference count

Shared_ptr specifies the destructor to be displayed. Therefore, the reset interface is provided to describe the target object when the target object has been created and the reference count reaches zero (that is, there is no control over shared_ptr to save the target object.

 
Template <typename T>
VoidShared_ptr_t <t>: reset ()
{
If(M_dest_ptr)
{
If(True= M_ref_count-> dec_and_check_zero ())
{
Delete m_ref_count;
Delete m_dest_ptr;
}
M_ref_count = NULL;
M_dest_ptr = NULL;
}
}
5. shared_ptr destructor

It is easy to reduce the reference count.

 
Template <typename T>
Shared_ptr_t <t> ::~ Shared_ptr_t ()
{
Reset ();
}
6. Use shared_ptr like the original pointer

Shared_ptr can be used in this way.

Struct foo_t {int ;}

Shared_ptr_t <foo_t> P (New foo_t ());

(* P). A = 100;

P-& gt; A = 100;

If (p) cout <"P not null! \ N ";

Therefore, the following interfaces are provided:

Template <typename T>
Typename shared_ptr_t <t >:: object_t & shared_ptr_t <t> ::Operator*()
{
Assert (null! = M_dest_ptr );
Return* M_dest_ptr;
}

Template <typename T>
Typename shared_ptr_t <t>: object_t * shared_ptr_t <t> ::Operator-> ()
{
Assert (null! = M_dest_ptr );
ReturnM_dest_ptr;
}

Operator bool () const
{
Return null! = M_dest_ptr;
}

7. Implement lock free reference count

Some atomic operation has been defined in GCC, but after reading the documents, it should be better to support Intel's platform, and the support for other platforms is not clear. Therefore, the atomic operation is encapsulated into a macro.

# DefineAtomic_add (src_ptr, V) (void) _ sync_add_and_fetch (src_ptr, V)
# DefineAtomic_sub_and_fetch (src_ptr, v) _ sync_sub_and_fetch (src_ptr, V)

The implementation of ref_count_t is simple:

 Class Ref_count_t
{
Typedef Volatile Long Atomic_t;
Public :
Ref_count_t ():
M_ref_num ( 1 )
{}
~ Ref_count_t ()
{}

Inline Void INC ()
{
Atomic_add (& m_ref_num, 1 );
}
Inline Bool Dec_and_check_zero ()
{
Return 0 = Atomic_sub_and_fetch (& m_ref_num, 1 );
}
Inline atomic_t size ()
{
Return M_ref_num;
}

Private :
Atomic_t m_ref_num;
};
# Endif
8. Thread Security

1. Multiple shared_ptr entries in a single thread point to different objects, which is safe.

2. Multiple shared_ptr entries in a single thread point to the same object, which is safe.

3. multi-threaded multiple operations different shared_ptr, pointing to different objects, safe.

4. multi-threaded multiple operations different shared_ptr, pointing to the same object, shared_ptr Security (that is, the reference count is maintained correctly), operations on the original object depend on the user.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.