diff options
Diffstat (limited to 'a6/noalloc.cc')
-rw-r--r-- | a6/noalloc.cc | 68 |
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(); + } +} |