简短回答:
几乎没有
长答案:
每当您需要在 32 位系统上拥有大于 2gb 的 char 向量时。在所有其他用例中,使用有符号类型比使用无符号类型更安全。
示例:
std::vector<A> data;
[...]
// calculate the index that should be used;
size_t i = calc_index(param1, param2);
// doing calculations close to the underflow of an integer is already dangerous
// do some bounds checking
if( i - 1 < 0 ) {
// always false, because 0-1 on unsigned creates an underflow
return LEFT_BORDER;
} else if( i >= data.size() - 1 ) {
// if i already had an underflow, this becomes true
return RIGHT_BORDER;
}
// now you have a bug that is very hard to track, because you never
// get an exception or anything anymore, to detect that you actually
// return the false border case.
return calc_something(data[i-1], data[i], data[i+1]);
size_t 的签名等效项是 ptrdiff_t,而不是 int。但在大多数情况下,使用int 仍然比 size_t 好得多。 ptrdiff_t 在 32 位和 64 位系统上是 long。
这意味着每当您与 std::containers 交互时,您总是必须在 size_t 之间进行转换,这不是很漂亮。但是在一个正在进行的本地会议上,c++ 的作者提到使用无符号 size_t 设计 std::vector 是一个错误。
如果您的编译器在从 ptrdiff_t 到 size_t 的隐式转换时向您发出警告,您可以使用构造函数语法使其显式:
calc_something(data[size_t(i-1)], data[size_t(i)], data[size_t(i+1)]);
如果只是想迭代一个集合,没有边界检查,使用基于范围的:
for(const auto& d : data) {
[...]
}
这里是 Bjarne Stroustrup(C++ 作者)going native 的一些话
对于某些人来说,STL 中的这种有符号/无符号设计错误是足够的理由,不使用 std::vector,而是使用自己的实现。