From 9058dd37ee3eda1dc004e07218cd8115e3fa4f09 Mon Sep 17 00:00:00 2001 From: Tyge Løvset Date: Thu, 23 Sep 2021 09:11:27 +0200 Subject: Added sptr_ex.c example + minors. --- examples/sptr_ex.c | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 examples/sptr_ex.c (limited to 'examples') diff --git a/examples/sptr_ex.c b/examples/sptr_ex.c new file mode 100644 index 00000000..4a0397ec --- /dev/null +++ b/examples/sptr_ex.c @@ -0,0 +1,65 @@ +// shared_ptr-examples.cpp +// based on https://docs.microsoft.com/en-us/cpp/cpp/how-to-create-and-use-shared-ptr-instances?view=msvc-160 + +#include +#include +#include + +forward_csptr(song, struct Song); +struct Test { + csptr_song song1; + csptr_song song2; +}; + +// ... + +struct Song +{ + cstr artist; + cstr title; +} typedef Song; + +Song Song_from(const char* artist, const char* title) + { return (Song){cstr_from(artist), cstr_from(title)}; } + +void Song_del(Song* s) { + printf("del: %s\n", s->title.str); + c_del(cstr, &s->artist, &s->title); +} + +#define i_val Song +#define F_tag song +#define i_cmp c_no_compare +#define i_del Song_del +#include + +#define i_val_csptr song +#include + +void example3() +{ + c_auto (cvec_song, v, v2) { + csptr_song songs[] = { + csptr_song_make(Song_from("Bob Dylan", "The Times They Are A Changing")), + csptr_song_make(Song_from("Aretha Franklin", "Bridge Over Troubled Water")), + csptr_song_make(Song_from("Thalia", "Entre El Mar y Una Estrella")) + }; + c_forrange (i, c_arraylen(songs)) + cvec_song_push_back(&v, songs[i]); + + c_foreach (s, cvec_song, v) + if (!cstr_equalto(s.ref->get->artist, "Bob Dylan")) + cvec_song_emplace_back(&v2, *s.ref); // calls csptr_song_clone() + + cvec_song_push_back(&v2, csptr_song_make(Song_from("Pink Floyd", "Dogs"))); + + c_foreach (s, cvec_song, v2) + printf("%s - %s: refs %zu\n", s.ref->get->artist.str, s.ref->get->title.str, + *s.ref->use_count); + } +} + +int main() +{ + example3(); +} \ No newline at end of file -- cgit v1.2.3