I thought the correct type for storing the difference between pointers was ptrdiff_t .
Thus, I am confused by the fact that my STL (msvc 2010) implements the function std::vector::size() . The type of the return value is size_t (this, in my opinion, corresponds to the standard, and, nevertheless, it is calculated as the difference of pointers:
// _Mylast, _Myfirst are of type pointer // size_type, pointer are inherited from allocator<_Ty> size_type size() const { return (this->_Mylast - this->_Myfirst); }
Obviously, there is a bit of metamagy going on to pinpoint the types size_type and pointer . To be sure what types they are, I tested this:
bool bs = std::is_same<size_t, std::vector<int>::size_type>::value; bool bp = std::is_same<int * , std::vector<int>::pointer>::value;
Compiling the following with /Wall gives me a signed-to-unsigned mismatch for mysize2 , but no warnings for mysize1 :
std::vector<int> myvector(100); int *tail = &myvector[99]; int *head = &myvector[ 0]; size_t mysize1 = myvector.size(); size_t mysize2 = (tail - head + 1);
Changing mysize2 to ptrdiff_t does not result in a warning. Changing the type of mysize1 to ptrdiff_t results in an unsigned-to-signed mismatch .
Obviously, I missed something ...
EDIT: I am not asking how to suppress a warning with cast or #pragma disable(xxx) . The problem I'm worried about is that size_t and ptrdiff_t can have different valid ranges (they run on my machine).
Consider std::vector<char>::max_size() . My implementation returns a max_size equal to std::numeric_limits<size_t>::max() . Since vector::size() creates an intermediate value of type ptrdiff_t before proceeding to size_t , it seems that there may be problems - ptrdiff_t not large enough to hold vector<char>::max_size() .