Skip to content

Commit 6f3c07f

Browse files
author
Donatien Garnier
committed
Optimize SharedPtr code
1 parent ac79b00 commit 6f3c07f

File tree

1 file changed

+8
-16
lines changed

1 file changed

+8
-16
lines changed

platform/SharedPtr.h

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ class SharedPtr {
7878
SharedPtr(T* ptr): _ptr(ptr), _counter(NULL) {
7979
// allocate counter on the heap so it can be shared
8080
if(_ptr != NULL) {
81-
_counter = (uint32_t*) malloc(sizeof(uint32_t));
81+
_counter = new uint32_t;
8282
*_counter = 1;
8383
}
8484
}
@@ -100,9 +100,7 @@ class SharedPtr {
100100
SharedPtr(const SharedPtr& source): _ptr(source._ptr), _counter(source._counter) {
101101
// increment reference counter
102102
if (_ptr != NULL) {
103-
core_util_critical_section_enter();
104-
(*_counter)++;
105-
core_util_critical_section_exit();
103+
core_util_atomic_incr_u32(_counter, 1);
106104
}
107105
}
108106

@@ -123,9 +121,7 @@ class SharedPtr {
123121

124122
// increment new counter
125123
if (_ptr != NULL) {
126-
core_util_critical_section_enter();
127-
(*_counter)++;
128-
core_util_critical_section_exit();
124+
core_util_atomic_incr_u32(_counter, 1);
129125
}
130126
}
131127

@@ -142,7 +138,7 @@ class SharedPtr {
142138

143139
if(ptr != NULL) {
144140
// allocate counter on the heap so it can be shared
145-
_counter = (uint32_t*) malloc(sizeof(uint32_t));
141+
_counter = new uint32_t;
146142
*_counter = 1;
147143
}
148144
}
@@ -215,17 +211,13 @@ class SharedPtr {
215211
* @details If count reaches zero, free counter and delete object pointed to.
216212
*/
217213
void decrement_counter() {
218-
if (_counter) {
219-
core_util_critical_section_enter();
220-
if (*_counter == 1) {
221-
core_util_critical_section_exit();
222-
free(_counter);
214+
if (_ptr != NULL) {
215+
uint32_t new_value = core_util_atomic_decr_u32(_counter, 1);
216+
if (new_value == 0) {
217+
delete _counter;
223218
_counter = NULL;
224219
delete _ptr;
225220
_ptr = NULL;
226-
} else {
227-
(*_counter)--;
228-
core_util_critical_section_exit();
229221
}
230222
}
231223
}

0 commit comments

Comments
 (0)