C++ Logo

std-proposals

Advanced search

Library facility for determining an object's memory use

From: Kyle Knoepfel <kyleknoepfel_at_[hidden]>
Date: Mon, 9 Nov 2020 21:27:44 -0600
I am sure this has been considered before, but I bring it up to in the off chance that it may spark some interest.

Evaluating memory usage within a program can be a tricky affair whenever one wants to learn how much a particular object contributes to the memory footprint. Sure, tools exist that track memory (de)allocations, etc., but I'm not aware of a way to easily glean how much memory a particular object is responsible for within a C++ program. This can be helpful for flagging expensive operations at runtime, poor library use, etc.

For example, sizeof() is great at reporting stack memory usage. However, novices, when typing sizeof(vector<int>), will be surprised to learn that the answer will be 24 bytes on a 64-bit machine, regardless of the number of elements or size of the value type. I'm wondering if anyone has proposed a library facility that would report a "total" memory footprint of an object (e.g.):

using namespace std::memory_literals; // Putative namespace that could support B, KiB, MiB, KB, GB, etc.

std::vector nums{1,2,4, 8};
auto mem = std::memory_use(nums);
assert(mem.stack == 24B);
assert(mem.heap == 4*sizeof(int));

Obviously there are the pointer situations:

auto num_p1 = new int{42};
assert(std::memory_use(num_p1).heap == sizeof(int));

auto num_p2 = num_p1;
assert(std::memory_use(num_p2).heap == sizeof(int));

auto num_p3 = std::shared_ptr<int>{num_p1}; // Good luckā€¦

So the reported memory wouldn't necessarily correspond to what the object is responsible for, but rather what memory is attributed in anyway with that object.

So...has this been considered before, and if not, why not?

Thanks!
Kyle Knoepfel

Received on 2020-11-09 21:27:48