How to find the memory used by any object

22,713

Solution 1

If you are looking for the full memory usage of an object, this can't be solved in general in C++ - while we can get the size of an instance itself via sizeof(), the object can always allocate memory dynamically as needed.

If you can find out how big the individual element in a container are, you can get a lower bound:

size = sizeof(map<type>) + sum_of_element_sizes;

Keep in mind though that the containers can still allocate additional memory as an implementation detail and that for containers like vector and string you have to check for the allocated size.

Solution 2

Short Answer: No

Long Answer:
-> The basic object yes. sizeof(<TYPE>) but this is only useful for limited things.
-> A container and its contained members: NO

If you make assumptions about the structures used to implement these objects you can estimate it. But even that is not really useful ( apart from the very specific case of the vector).

The designers of the STL deliberately did not define the data structures that should be used by these containers. There are several reasons for this, but one of them (in my opinion) is to stop people making assumptions about the internals and thus try and do silly things that are not encapsulated by the interface.

So the question then comes down to why do you need to know the size?
Do you really need to know the size (unlikely but possible).

Or is there a task you are trying to achieve where you think you need the size?

Solution 3

If you're looking for the actual block of memory, the numerical value of a pointer to it should be it. (Then just add the number of bytes, and you have the end of the block).

Share:
22,713
ARV
Author by

ARV

learning forever...

Updated on February 12, 2020

Comments

  • ARV
    ARV about 4 years
    class Help
    {
    public:
            Help();
            ~Help();
    
            typedef std::set<string> Terms;
            typedef std::map<string, std::pair<int,Terms> > TermMap;
            typedef std::multimap<int, string, greater<int> > TermsMap;
    
    private:
    
            TermMap  terms;
            TermsMap    termsMap;
    };
    

    How can we find the memory used (in bytes) by the objects term and termsMap. Do we have any library ?