Skip to content

Instantly share code, notes, and snippets.

@edenhill
Created October 1, 2015 07:31
Show Gist options
  • Save edenhill/038d03088c1edc1aedae to your computer and use it in GitHub Desktop.
Save edenhill/038d03088c1edc1aedae to your computer and use it in GitHub Desktop.
#if !DEBUG_SHARED_PTR
/**
* The non-debug version of shared_ptr is simply a reference counting interface
* without any additional costs and no dereferencing.
*/
#define rd_shared_ptr_t RD_UNUSED void
#define rd_shared_ptr_get(OBJ,REFCNT) \
(rd_refcnt_add(REFCNT), (rd_shared_ptr_t *)(OBJ))
#define rd_shared_ptr_obj(SPTR,TYPE) (TYPE)(SPTR)
#define rd_shared_ptr_put(SPTR,REF,DESTRUCTOR) \
rd_refcnt_destroywrapper(REF,DESTRUCTOR)
#else /* DEBUG_SHARED_PTR: */
typedef struct rd_shared_ptr_s {
void *obj;
} rd_shared_ptr_t;
static __inline RD_UNUSED
__attribute__((warn_unused_result))
rd_shared_ptr_t *rd_shared_ptr_get0 (const char *func, int line, void *obj) {
rd_shared_ptr_t *sp = rd_calloc(1, sizeof(*sp));
sp->obj = obj;
return sp;
}
#define rd_shared_ptr_get(OBJ,REF) \
(rd_refcnt_add(REF), rd_shared_ptr_get0(__FUNCTION__,__LINE__,OBJ))
#define rd_shared_ptr_obj(SPTR,VAR) *(VAR) = (typeof(*(VAR)))((SPTR)->obj)
#define rd_shared_ptr_put(SPTR,REF,DESTRUCTOR) do { \
if (rd_refcnt_sub(REF) == 0) { \
DESTRUCTOR; \
rd_free(SPTR); \
} \
} while (0)
#endif /* DEBUG_SHARED_PTR */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment