The previous answers provided are incomplete since they only mention number of bytes, but not number of objects.
The documentation for max_size says the function should return "the maximum theoretically possible value of n, for which the call allocate(n, 0) could succeed," where n is the number of objects. It also says that for some allocator implementations it should return
std::numeric_limits<size_type>::max() / sizeof(value_type)
rather than
std::numeric_limits<size_type>::max()
The STL containers (e.g. - std::vector
, std::map
, or std::list
) use max_size to calculate container size in terms of object count, not byte count. Therefore, max_size()
should not return the number of bytes available on the operating system, but use the number of available bytes to calculate the number of objects the allocator can hold.
If you wrote an allocator class for STL containers, you could implement the max_size()
function like this to provide an accurate object count instead of over-estimating by using std::numeric_limits<size_type>::max()
.
size_type max_size() const
{
const unsigned long long bytesAvailable = GetTotalAvailableMemory();
const unsigned long long maxPossibleObjects = bytesAvailable / sizeof(value_type);
return maxPossibleObjects;
}
You can implement the GetTotalAvailableMemory()
like these functions depending on your operating system. Either will return the number of unallocated bytes which a program's process may use.
#if defined(unix) || defined(__unix__) || defined(__unix)
#include <unistd.h>
unsigned long long GetTotalAvailableMemory()
{
const long pageCount = sysconf( _SC_PHYS_PAGES );
const long pageSize = sysconf( _SC_PAGE_SIZE );
const unsigned long long totalBytes = pageCount * pageSize;
return totalBytes;
}
#endif
#if defined(_WIN64) || defined(_WIN64)
#include <windows.h>
unsigned long long GetTotalAvailableMemory()
{
MEMORYSTATUSEX status;
status.dwLength = sizeof( status );
GlobalMemoryStatusEx( &status );
return status.ullAvailVirtual;
}
#endif