How to determine C ++ object memory at runtime

I am trying to determine the size of an object at runtime. sizeof does not work because it returns 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, not ~ 1 GB. How to determine the size of foo at runtime? Thanks in advance.

+7
source share
3 answers

You need to take care of 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 must use the smart pointer container to manage dynamically allocated objects so that you do not have to manually manage their lifetimes. Here I demonstrated the use of scoped_array , which is a very useful container. You can also use shared_array or use shared_ptr with user deletion.

+5
source

Foo size is constant. The ~ 1 GB symbol does not apply to the object technically, only a pointer to it. Symbols are said to belong to the object, because the object is responsible for allocating and freeing memory for them. C ++ does not provide functions that let you know how much memory an object has allocated. You must follow this yourself.

+5
source

The size of the object is 4 bytes on your system. However, the object uses additional resources, such as 1 GB of memory.

+1
source

All Articles