The documentation for max_size says that the function should return "the maximum theoretically possible value of n for which the call allocates (n, 0) can succeed", where n is the number of objects.
STL containers (for example, std :: vector, std :: map, or std :: list) use max_size to calculate the size of the container based on the number of objects, not the number of bytes. Therefore, max_size () should not return the number of bytes available on the operating system, but use the number of bytes available to calculate the number of objects that the allocator can hold.
If you wrote a dispenser class for STL containers, you can implement a max_size () function like this to provide an accurate number of objects instead of being reevaluated with 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 GetTotalAvailableMemory () as these functions, depending on your operating system. Any of them will return the number of unallocated bytes that the software process can 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
Richs source share