Custom new and delete based on policy Mode

Source: Internet
Author: User

Background
In the design of object-oriented classes, sometimes in order to enhance efficiency, especially when a large number of small objects are constructed, in order to improve memory fragmentation, You need to implement the memory management of the objects by yourself, to replace the default distribution and Release Behaviors of the system, that is, global new and delete. In accordance with the c ++ standard, when customizing the exclusive new and delete classes, in order to reduce the troubles and problems of the customer's code usage, you need to consider simultaneously customizing simple (normal new) three new conditions: placement new and nothrow new, as well as the three delete conditions matched with them, in addition, there are three scenarios for the corresponding arrays new [] and delete. In interface design, operator new and operator delete versions are used in each scenario. In memory management, the specific object space allocation and release are flexible, therefore, this part can be implemented as a policy mode. By changing and replacing different memory management policies, you can easily obtain different memory allocation and release behaviors without changing the class code. To facilitate customization of the new and delete classes, you can inherit from an interface base class template and automatically obtain this feature. This base class template implements new, delete for a single object and new and delete for an object array. The template parameters are exactly the memory management policy class. Its design constraints are as follows:
1) The static member Methods malloc and free must exist. Their Parameters and return values are consistent with those of the C library malloc and free.
2) malloc only allocates space. If the allocation is successful, Initialization is not required. Otherwise, NULL is returned if the allocation fails. An exception cannot be thrown because the normal new syntax throws a std: bad_alloc exception if the allocation fails, nothrow new returns NULL. Both of these two methods enable flexible on-demand detection of Customer Code. free only releases or returns space.
3) internal implementation of malloc and free is flexible and customized by application developers.

Components
The new_delete_policy_base and object_pool_impl basic components are implemented here. The Code is as follows. The former is a base class template of the new and delete interfaces that supports memory management policy customization, the constructor and destructor of the objects inherited from this class are customized. The latter is a non-intrusive Object pool class template that supports memory management policies, it can be directly used to construct certain types of objects, including the built-in basic data types, which do not need to be inherited from new_delete_policy_base.
1 template <class Alloc>
2 class new_delete_policy_base
3 {
4 public:
5 static void * operator new (size_t size) throw (std: bad_alloc)
6 {
7 void * ptr = Alloc: malloc (size );
8 if (NULL = ptr ){
9 throw std: bad_alloc ();
10}
11 return ptr;
12}
13
14 static void * operator new (size_t size, void * ptr) throw ()
15 {return ptr ;}
16
17 static void * operator new (size_t size, const std: nothrow_t &) throw ()
18 {return Alloc: malloc (size );}
19
20 static void operator delete (void * ptr) throw ()
21 {Alloc: free (ptr );}
22
23 static void operator delete (void * ptr, const std: nothrow_t &) throw ()
24 {Alloc: free (ptr );}
25
26 static void operator delete (void *, void *) throw ()
27 {}
28
29 static void * operator new [] (size_t size) throw (std: bad_alloc)
30 {return operator new (size );}
31
32 static void * operator new [] (size_t size, void * ptr) throw ()
33 {return ptr ;}
34
35 static void * operator new [] (size_t size, const std: nothrow_t &) throw ()
36 {return operator new (size, std: nothrow );}
37
38 static void operator delete [] (void * ptr) throw ()
39 {operator delete (ptr );}
40
41 static void operator delete [] (void * ptr, const std: nothrow_t &) throw ()
42 {operator delete (ptr );}
43
44 static void operator delete [] (void *, void *) throw ()
45 {}
46 };
47
48 template <class Alloc>
49 class object_pool_impl
50 {
51 public:
52 template <typename T>
53 static T * construct ()
54 {
55 T * const p = static_cast <T *> (Alloc: malloc (sizeof (T )));
56 try {new (p) T ();}
57 catch () {Alloc: free (p); throw ;}
58 return p;
59}
60
61 template <typename T>
62 static void destroy (T * const ptr)
63 {
64 ptr-> ~ T ();
65 Alloc: free (ptr );
66}
67 };

Application
In the following code, mem_pool is a memory pool implemented based on the Free List mechanism. quick_object inherits from new_delete_policy_base <mem_pool> to demonstrate custom new and delete behaviors. The _ THROW_EXCEPTION macro is used to block code, test whether the corresponding operator delete is called when the object space is successfully allocated but the constructor throws an exception. Ensure that the memory space is released. normal_object is an empty class and does not inherit from new_delete_policy_base <mem_pool>, demonstrate Object pool construction and object destruction.
1 class quick_object: public new_delete_policy_base <mem_pool>
2 {
3 public:
4 quick_object ()
5 {
6 # ifdef _ THROW_EXCEPTION
7 throw 0;
8 # endif
9 cout <"quick_object ()" <endl;
10}
11 ~ Quick_object ()
12 {
13 cout <"~ Quick_object () "<endl;
14}
15 };
16
17 class normal_object
18 {
19 public:
20 normal_object ()
21 {
22 cout <"normal_object ()" <endl;
23}
24 ~ Normal_object ()
25 {
26 cout <"~ Normal_object () "<endl;
27}
28 };
29
30 /**
31 * the following code, if quick_object's construct function throw exception, then result in
32 * c/c ++ Run-time system call operator delete correspond to operator new automaticlly.
33 */
34 static void unit_test_new_delete_policy ()
35 {
36 quick_object * obj = NULL;
37
38 try {
39 obj = new quick_object; // call simple new
40 delete obj; // call simple delete
41} catch (){
42 // call simple delete
43}
44
45 try {
46 obj = new (std: nothrow) quick_object; // call nothrow new
47 delete obj; // call simple delete
48} catch (){
49 // call nothrow delete
50}
51
52 try {
53 char ptr [sizeof (quick_object)];
54 obj = new (ptr) quick_object; // call placement new
55} catch (){
56 // call placement delete
57}
58
59 try {
60 obj = new quick_object [10]; // call simple new []
61 delete [] obj; // call simple delete []
62} catch (){
63 // call simple delete []
64}
65
66 try {
67 obj = new (std: nothrow) quick_object [10]; // call nothrow new []
68 delete [] obj; // call simple delete []
69} catch (){
70 // call nothrow delete []
71}
72
73 try {
74 char ptr [sizeof (quick_object [10])];
75 obj = new (ptr) quick_object [10]; // call placement new []
76} catch (){
77 // call placement delete []
78}
79}
80
81 /**
82 * class quick_object is inherited from class new_delete_policy_base <mem_pool> that has implement
83 * operator new and delete, so that call placement new in template member construct of class obj_pool.
84 */
85 static void unit_test_obj_pool ()
86 {
87 typedef object_pool_impl <mem_pool> obj_pool;
88
89 try {
90 quick_object * obj = obj_pool: construct <quick_object> ();
91 obj_pool: destroy (obj );
92} catch (){
93
94}
95 // class normal_object's construct function do not throw exception.
96 normal_object * obj = obj_pool: construct <normal_object> ();
97 obj_pool: destroy (obj );
98}

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.