summaryrefslogtreecommitdiff
path: root/a6/noalloc.cc
diff options
context:
space:
mode:
authorBent Bisballe Nyeng <deva@aasimon.org>2023-08-04 21:30:35 +0200
committerBent Bisballe Nyeng <deva@aasimon.org>2023-08-04 21:30:35 +0200
commitb4e8a41aca5a22fc02da3b1a29ca10e4d472b6c7 (patch)
tree2cfab980424343c0daed8ea342f416e437fc0bfc /a6/noalloc.cc
parent345480d2c0647a1a4bf8b7915d78155a261ea988 (diff)
A6: WIP
Diffstat (limited to 'a6/noalloc.cc')
-rw-r--r--a6/noalloc.cc68
1 files changed, 68 insertions, 0 deletions
diff --git a/a6/noalloc.cc b/a6/noalloc.cc
new file mode 100644
index 0000000..0da4025
--- /dev/null
+++ b/a6/noalloc.cc
@@ -0,0 +1,68 @@
+#include <iostream>
+#include <functional>
+
+// Universal allocator
+namespace memory
+{
+void* ptr{};
+}
+
+void* operator new([[maybe_unused]]std::size_t n) // throw(std::bad_alloc) - don't throw
+{
+ std::cout << "new\n";
+ // Just return the supplied stack pointer
+ return memory::ptr;
+}
+
+void operator delete(void*) throw()
+{
+ std::cout << "delete\n";
+ // Do nothing. actual memory is allocated on the stack
+}
+
+void operator delete(void*, std::size_t) throw()
+{
+ std::cout << "delete[]\n";
+ // Do nothing. actual memory is allocated on the stack
+}
+
+//void foo() __attribute__((noinline))
+int main()
+{
+ char buf[256];
+ memory::ptr = buf;
+
+ std::cout << " ** strings:\n";
+ { // strings
+ // now this is ok:
+ std::string str(32, 'a');
+ std::cout << str << '\n';
+
+ std::string str2(24, 'b');
+ std::cout << str << '\n'; // the contents of str has been overwritten
+
+ // this will also allocate, but supply the same buffer - ok
+ str = "hello world hello world hello world";
+
+ // this is also ok, but due to SSO
+ std::string sso{"hello"};
+ }
+
+ std::cout << " ** lambdas:\n";
+ { // lambdas
+ std::function<int()> f;
+ {
+ char foo[16]{};
+ f = [=]()__attribute__((noinline)) // capture up 16 bytes - ok
+ {
+ int i = 0;
+ for(auto v : foo)
+ {
+ i += v;
+ }
+ return i;
+ }; // capture foo by copy - inlined
+ }
+ [[maybe_unused]]auto x = f();
+ }
+}