我认为用于存储指针之间差异的正确类型是ptrdiff_t
。
因此,我对我的STL
(msvc 2010)实现其std::vector::size()
函数的方式感到困惑。返回类型为size_t
(据我所理解,这是标准规定的),但它是通过指针之间的差异计算出来的:
// _Mylast, _Myfirst are of type pointer
// size_type, pointer are inherited from allocator<_Ty>
size_type size() const
{
return (this->_Mylast - this->_Myfirst);
}
显然,为了确定size_type
和pointer
的确切类型,需要进行一些元魔法。为了“确保”它们的类型,我检查了以下内容:
bool bs = std::is_same<size_t, std::vector<int>::size_type>::value;
bool bp = std::is_same<int * , std::vector<int>::pointer>::value;
// both bs and bp evaluate as true, therefore:
// size_type is just size_t
// pointer is just int*
使用
/Wall
编译以下内容,会出现signed-to-unsigned mismatch
的警告,但是对于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);
将
mysize2
的类型更改为ptrdiff_t
不会产生警告。
将mysize1
的类型更改为ptrdiff_t
会产生一个unsigned-to-signed mismatch
警告。
显然我漏掉了什么...
编辑:我不是在问如何通过强制转换或#pragma disable(xxx)
来抑制警告。我关心的问题是size_t
和ptrdiff_t
可能具有不同的允许范围(在我的机器上确实如此)。
考虑std::vector<char>::max_size()
。我的实现返回一个等于std::numeric_limits<size_t>::max()
的max_size
。由于vector::size()
在强制转换为size_t
之前创建了一个ptrdiff_t
类型的中间值,因此似乎可能存在问题- ptrdiff_t
不足以容纳vector<char>::max_size()
。