I'm trying to determine the size of an object at runtime. sizeof doesn't work because this returns the size at compile time. Here is an example of what I mean:
class Foo
{
public:
Foo()
{
c = new char[1024*1024*1024];
}
~Foo()
{
delete[] c;
}
private:
char *c;
};
In this case, sizeof(Foo)
will be 4 bytes and not ~1GB. How can I determine the size of Foo at runtime? Thanks in advance.
The size of Foo is constant. The ~1GB of chars does not technically belong to the object, just the pointer to it does. The chars are only said to be owned by the object, because the object is responsible for allocating and deallocating memory for them. C++ does not provide features that allow you to find out how much memory an object has allocated. You have to keep track of that yourself.
You need to keep track of it yourself somehow. For example:
struct Foo
{
Foo()
: elements(1024 * 1024 * 1024)
{
c.reset(new char[elements]);
}
boost::scoped_array<char> c;
int elements;
};
Note that you should use a smart pointer container for managing dynamically allocated objects so that you don't have to manage their lifetimes manually. Here, I've demonstrated use of scoped_array
, which is a very helpful container. You can also use shared_array
or use shared_ptr
with a custom deleter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With