Add a lifetime object to test scopes
dblume

dblume commited on 2024-09-13 20:15:11
Showing 3 changed files, with 77 additions and 1 deletions.

... ...
@@ -7,7 +7,7 @@ OBJDIR=obj
7 7
 
8 8
 SOURCES=main.cpp main_helper.cpp ui/widget.cpp scoped_set_adder.cpp \
9 9
 	thread_with_lambda.cpp thread_manager.cpp deadlock/deadlock.cpp \
10
-	next_power_of_two.cpp mmmm.cpp copilot_serialize.cpp
10
+	next_power_of_two.cpp mmmm.cpp copilot_serialize.cpp lifetime.cpp
11 11
 # //OBJECTS=$(OBJDIR)$(SOURCES:.cpp=.o)
12 12
 OBJECTS=$(foreach bname, $(basename $(SOURCES)), $(OBJDIR)/$(bname).o)
13 13
 EXECUTABLE=testcode
... ...
@@ -0,0 +1,64 @@
1
+#include "lifetime.h"
2
+#include <cstdio>
3
+#include <array>
4
+// From C++ Weekly with Jason Turner
5
+// https://www.youtube.com/watch?v=6SaUwqw4ueE
6
+//
7
+// Test with:
8
+// ls -1 lifetime* | entr sh -c 'g++ -Wall -std=c++17 lifetime.cpp && valgrind -q --leak-check=yes --show-leak-kinds=all ./a.out'
9
+
10
+Lifetime::Lifetime()
11
+{
12
+    std::puts("Lifetime() // default ctor"); 
13
+}
14
+
15
+Lifetime::~Lifetime()
16
+{
17
+    std::puts("~Lifetime() // destructor"); 
18
+}
19
+
20
+Lifetime::Lifetime(const Lifetime &)
21
+{
22
+    std::puts("Lifetime(const Lifetime &) // copy ctor"); 
23
+}
24
+
25
+Lifetime::Lifetime(Lifetime &&)
26
+{
27
+    std::puts("Lifetime(Lifetime &&) // move ctor"); 
28
+}
29
+
30
+Lifetime &Lifetime::operator=(Lifetime &&)
31
+{
32
+    std::puts("operator=(const Lifetime &&) // move assign"); 
33
+    return *this;
34
+}
35
+
36
+Lifetime &Lifetime::operator=(const Lifetime &)
37
+{
38
+    std::puts("operator=(const Lifetime &) // copy assign"); 
39
+    return *this;
40
+}
41
+
42
+/*
43
+int main()
44
+{
45
+#if 0
46
+    Lifetime l1;
47
+    Lifetime l2;
48
+    std::array<Lifetime, 2> a{l1, l2};
49
+#elif 1
50
+    Lifetime l1;
51
+    Lifetime l2;
52
+    std::array<Lifetime, 2> a{std::move(l1), std::move(l2)};
53
+#else
54
+    auto make_lifetime = [](const int value) {
55
+        // Benefits from return value optimization
56
+        Lifetime l;
57
+        l.data_ = value;
58
+        return l;
59
+    };
60
+
61
+    std::array<Lifetime, 2> a{make_lifetime(42), make_lifetime(43)};
62
+#endif
63
+}
64
+*/
... ...
@@ -0,0 +1,12 @@
1
+#pragma once
2
+
3
+struct Lifetime {
4
+    Lifetime();
5
+    ~Lifetime();
6
+    Lifetime(const Lifetime &);
7
+    Lifetime(Lifetime &&);
8
+    Lifetime &operator=(Lifetime &&);
9
+    Lifetime &operator=(const Lifetime &);
10
+
11
+    int data_;
12
+};
0 13