summaryrefslogtreecommitdiff
path: root/a6/noalloc.cc
blob: 0da4025f90bc516e7566cfd9e9277e829d827a1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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();
	}
}