简体   繁体   中英

How can I know the allocated memory size of a std::vector?

I understand that we can use size() function to obtain the vector size, for example:

   std::vector<in> abc;
   abc.resize(3);
   abc.size();

The my question is how can I know the memory size of a vector? Take an example:

std::vector<int> abc;
abc.reserve(7);
//the size of memory that has been allocated for abc

You use the member function capacity() to obtain the allocated capacity

std::vector<int> abc;
abc.reserve(7);
std::cout << abc.capacity() << std::endl;

To get the memory allocated by in bytes, You can do:

sizeof(int) * abc.capacity();

This is given, that you know your value_type is int . If you don't

sizeof(decltype(abc.back())) * abc.capacity();

The real answer is that you can't. Others have suggested ways that will often work, but you can't depend on capacity reflecting in any way the actual memory allocated.

For one thing, the heap will often allocate more memory than was requested. This has to do with optimizations against fragmenting, etc... vector has no way of knowing how much memory was actually allocated, only what it requested.

So capacity at best gives you a very rough estimate.

There are strong statements on the memory being contiguous, and so the size is

sizeof( abc[0] ) * abc.capacity();

or

(  (char*)(&abc[1]) - (char*)(&abc[0] ) ) * abc.capacity();

Since std::vector can store complex objects (such as std::string), which have their internal memory management and may allocate additional memory, determining the total memory usage can be hard.

For a vector containing simple objects such as int , the suggested solution using capacity and sizeof will work though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM