-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared_ptr.h
44 lines (37 loc) · 1.22 KB
/
shared_ptr.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#pragma once
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
/* Usage : this is very simple. To create a shared_ptr, you just need to
* call the make_shared function with the type of your pointer, and the
* number of element you want to allocate.
* To pass a pointer from a function to another, there is to cases :
* - From caller to callee : you just need to pass the pointer as is.
* - From callee to caller : you need to return the pointer with
* reference(ptr)
*/
struct meta {
size_t count;
};
void clean_this_shit(void *ptr)
{
char *t = *(char **)ptr;
struct meta *tmp = (struct meta *)(t - sizeof(*tmp));
if ( !(--tmp->count) )
free(tmp);
}
#define shared __attribute__((cleanup(clean_this_shit)))
#define make_shared(Type, elt) ({ \
struct meta tmp_s = { \
.count = 1 \
}; \
char *res = malloc((sizeof(Type) * (elt)) + sizeof(struct meta)); \
memcpy(res, &tmp_s, sizeof(tmp_s)); \
(void *)(res + sizeof(tmp_s)); \
})
#define reference(ptr) ({\
char *t = (char *)ptr; \
struct meta *tmp = (struct meta *)(t - sizeof(struct meta)); \
tmp->count++; \
ptr; \
})