Finding out the total memory used for allocating an object

S

sfs

Hi All,

Let's say I want to find out the total memory consumed by the following
class A. Please note that I don't want the size of the class.

Class A
{
private:
B* mwm1;
C* mem2;
}

Now class B and class C are classes which may contain some more
pointers to objects. For example,

class B
{

private:
int *k;
float *l;
D* m; //D is a class
}

class C
{

private:
int *k;
float *l;
E *g; //E is a class.
}

Regards.
Subhransu
 
P

Phlip

sfs said:
Let's say I want to find out the total memory consumed by the following
class A.

There is no portable way to get this information. Your code is expected to
know its own sizes and such - that's a feature of C++.

Non-portably, you could use a function with a name like heapwalk(). Examine
your heap before and after new-ing the object and all its dependents.

Now why do you need to know this information? A memory profiler, such as
Valgrind, can tell you about all your memory blocks...
 
M

mailforpr

How about this way:

class Know_your_size
{
public:
virtual int get_heap_size() const=0;
virtual ~Know_your_size() {}
};

class A: public Know_your_size
{
private:
B* mwm1; //both B and C too inherit from Know_your_size
C* mem2;
public:
int get_heap_size() const
{
return mwm1->get_heap_size() + mem2->get_heap_size();
}
};

And so on.
 
M

mailforpr

Of course, a std::string doesn't inherit from Know_your_size.

So a final implementation of get_heap_size() could look like this:

class F:public Know_your_size
{
private:
std::string str;
int i;
public:
int get_heap_size() const
{
return sizeof(int) + sizeof(std::string) +
str.size()*sizeof(char);
}
};

Of course, this will only provide you a vague amount of the used
memory. There is most likely much more memory allocated dynamically by
the string class which can't be accessed "legally".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top