#include #include // 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 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(); } }