Created
April 26, 2012 07:00
-
-
Save pluskid/2496958 to your computer and use it in GitHub Desktop.
Efficient ref-counting prototype for SGVector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
class SGVector | |
{ | |
public: | |
SGVector(int32_t len) | |
{ | |
int32_t size = sizeof(T)*len + sizeof(int32_t); | |
uchar *memory = malloc(size); | |
m_buffer = memory + sizeof(int32_t); | |
int32_t *ref_count = get_ref_count_pointer(); | |
*ref_count = 0; | |
} | |
SGVector(const SGVector& o) | |
{ | |
m_len = o.m_len; | |
m_buffer = o.m_buffer; | |
// update ref-count | |
int32_t *ref_count = get_ref_count_pointer(); | |
*ref_count += 1; | |
} | |
~SGVector() | |
{ | |
// update ref-count | |
int32_t *ref_count = get_ref_count_pointer(); | |
*ref_count -= 1; | |
if (*ref_count <= 0) | |
free(ref_count); | |
} | |
private: | |
int32_t *get_ref_count_pointer() | |
{ | |
// ref-counting is stored before the buffer | |
return ((uchar *)m_buffer) - sizeof(int32_t); | |
} | |
T *m_buffer; | |
int32_t m_len; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment