Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

c++ - How to find the memory used by any object

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...