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
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#include <stdio.h>
#include <string.h>
void int_drop(int* x) {
printf("drop: %d\n", *x);
}
// csptr implements its own clone method using reference counting,
// so 'i_valfrom' need not be defined (will be ignored).
#define i_type iref // set type name to be defined (instead of 'csptr_int')
#define i_val int
#define i_drop int_drop // optional, just to display the elements destroyed
#include <stc/csptr.h> // iref
#define i_key_bind iref // note: use i_key_bind instead of i_key for csptr/cbox elements
#include <stc/csset.h> // csset_iref (like: std::set<std::shared_ptr<int>>)
#define i_val_bind iref // note: as above.
#include <stc/cvec.h> // cvec_iref (like: std::vector<std::shared_ptr<int>>)
int main()
{
c_auto (cvec_iref, vec) // declare and init vec, call cvec_iref_drop() at scope exit
c_auto (csset_iref, set) // declare and init set, call csset_iref_drop() at scope exit
{
const int years[] = {2021, 2012, 2022, 2015};
c_forrange (i, c_arraylen(years))
cvec_iref_push_back(&vec, iref_new(years[i]));
printf("vec:");
c_foreach (i, cvec_iref, vec) printf(" %d", *i.ref->get);
puts("");
// add odd numbers from vec to set
c_foreach (i, cvec_iref, vec)
if (*i.ref->get & 1)
csset_iref_emplace(&set, *i.ref); // copy shared pointer => increments counter.
// erase the two last elements in vec
cvec_iref_pop_back(&vec);
cvec_iref_pop_back(&vec);
printf("vec:");
c_foreach (i, cvec_iref, vec) printf(" %d", *i.ref->get);
printf("\nset:");
c_foreach (i, csset_iref, set) printf(" %d", *i.ref->get);
c_autovar (iref p = iref_clone(vec.data[0]), iref_drop(&p)) {
printf("\n%d is now owned by %ld objects\n", *p.get, *p.use_count);
}
puts("\nDone");
}
}
|