Conversation

en.cppreference.com/w/cpp/memory/n is a decent approach. An implementation as an example: github.com/GrapheneOS/har. It doesn't work well in C++ because it's only for new and people don't use it whenever they call malloc, mmap, etc. but it's an approach that can work well for the common case.
2
So, for example, modern malloc implementations can usually drop cached pages via MADV_DONTNEED in a memory exhaustion situation. In normal usage, they would generally use MADV_FREE. The same thing applies to many other allocators and caches. Android & Windows have APIs for this.
1
1
On Windows, you can mark a range of memory with MEM_RESET that you aren't currently using and it can be freed if there's memory pressure. You call MEM_RESET_UNDO when you want to use it again, and it tells you if your memory was released. Android has pin/unpin for ashmem.
1
1
Chromium, Firefox, etc. use this and it's just stubbed out for non-Android Linux since there's nothing to use. MADV_FREE is much nicer for a performance-oriented malloc though, because when you wouldn't want to lock in the remaining faulted pages when you hand out allocations.
1
1
I find it weird that it isn't the norm for allocators to at least attempt this internally, for their internal caches, especially since this only impacts the cold path for handling allocation failure and shouldn't add a single branch or instruction to main code paths / sections.
1
1
It's also so typical of C++ to define that for new, while ignoring malloc, even though having it as a malloc feature would be strictly superior in the real world where new is implemented via malloc and many libraries, applications, etc. are still being used calling malloc...