QVector和std::vector的size方法

4
`QVector`的`size`方法返回类型是`int`,而`std::vector`中的同名方法返回类型是`unsigned`。为什么会有这种差异?难道`unsigned`不是保存大小的正确方式吗,因为它不能为负数?

2
0仍然是一个有效的大小,在某些情况下,您可能希望使用-1来表示无效。 - dtech
此外,常见的做法是在循环中使用 int,因此如果将 int 与 uint 进行比较,则会收到编译器警告。仅限于无符号整数大小的一半并不是那么显著的缺点。 - dtech
1
@ddriver 人们通常会感到惊讶,因为这违反了STL普遍使用size_t的惯例,而不是任何实际或逻辑上的原因。 - cmannett85
3
一个无效大小的容器是什么? - Frank Osterfeld
1个回答

6

因为他们在1999年讨论了这个问题,得出结论int是更好的选择,因为返回uint的函数数量相对较少,而且他们对警告感到不满:

Subject: Re: killing uint as return type in Qt.
From: Alex Sandro Queiroz e Silva <asandro@xxxxxxxxxxxxx>
Date: Wed, 17 Mar 1999 15:29:37 -0300 (EST)
Cc: qt-interest@xxxxxxxx
To: Arnt Gulbrandsen <arnt@xxxxxxxx>

On 17 Mar 1999, Arnt Gulbrandsen wrote:

About 0.15% of the functions in Qt return uint. Most of those are called QMumble::size() or QMumble::count(). These functions never need to return a negative number, so really, uint is the right type for them to return.

But it's a nuisance, to me at least. I keep comparing them with ints, putting them in variables that -can- contain negative numbers, and so on. I've written

 if ( blah->count() < i )

and gotten compiler warning too many times already.

So I am considering changing the return type for these functions to int in Qt 2.0. What do you think? You're the users - do you want correctness and total backward compatibility or would you prefer more convenience?

--Arnt

I think this time convenience is better, we all now the kind of results we may get from this methos, so...

-- Alex asandro@lcg.dc.ufc.br


rubenvb:为什么说是“愚蠢”的选择?(顺便说一句,我现在考虑过后,基于我之前的Java经验,我认为这是正确的选择。Uint的初衷是好的,但Java表明它在实践中并不是很有用。) - arnt
@arnt:等一下。你是我引用的那个“arnt”吗?哇。话虽如此,我想rubenvb喜欢正确的类型适用于正确的情况。*::size()永远不会产生负值。另一方面,即使是Haskell的length :: [a] -> Int也没有使用无符号类型Word,所以经常会根据方便性做出决策。(另外,你有邮件列表的镜像吗?) - Zeta
我是那个arnt,是的,我喜欢重新考虑这样的决定并尝试学习。在我看来,size()被限制在比[0,UINT_MAX]更小的范围内,它被限制在[0,x],其中x是一个可以malloc的对象数量,如果malloc是空间有效的,则可能为UINT_MAX的5-10%,对象非常小且指针宽度与整数相同。这意味着size()的返回值适合于int和uint的共享子集,并且两种类型都同样适用。毕竟,应该使用完全跨越可能值的最小类型,而int和uint都符合该测试。 - arnt
我很抱歉,我没有任何镜像。但是你可以在我的Github账户上找到旧源代码的镜像。 - arnt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接