【发布时间】:2017-03-27 07:23:58
【问题描述】:
我正在阅读 Andrew Koenig 和 Barbara E. Moo 的“Accelerated C++”一书,我对第 2 章中的主要示例有一些疑问。代码可以总结如下,并且正在编译时没有警告/错误g++:
#include <string>
using std::string;
int main()
{
const string greeting = "Hello, world!";
// OK
const int pad = 1;
// KO
// int pad = 1;
// OK
// unsigned int pad = 1;
const string::size_type cols = greeting.size() + 2 + pad * 2;
string::size_type c = 0;
if (c == 1 + pad)
{;}
return 0;
}
但是,如果我将const int pad = 1; 替换为int pad = 1;,g++ 编译器将返回警告:
warning: comparison between signed and unsigned integer expressions [-Werror=sign-compare]
if (c == 1 + pad)
如果我将const int pad = 1; 替换为unsigned int pad = 1;,g++ 编译器将不会返回警告。
我明白为什么 g++ 返回警告,但我不确定以下三点:
- 使用
unsigned int与std::string::size_type进行比较是否安全?在这种情况下,编译器不会返回警告,但我不确定它是否安全。 - 为什么编译器没有给出原始代码
const int pad = 1的警告。编译器是否会自动将变量pad转换为unsigned int? - 我也可以用
string::size_type pad = 1;替换const int pad = 1;,但在我看来,变量pad的含义并没有真正与字符串大小相关联。不过,在这种情况下,这是否是避免在比较中出现不同类型的最佳方法?
【问题讨论】:
-
来自 msdn :
basic_string::size_type=>typedef typename allocator_type::size_type size_type;=> 无符号整数类型,可以表示字符串中元素和索引的数量。 (msdn.microsoft.com/library/5ddehwe8.aspx)。所以使用 unsinged int 可能是一个好方法 -
@Fefux 我不相信微软是 C/C++ 标准的权威来源。多年来,他们对标准有足够的“创造性”解释......
-
if ( (int)c == pad + 1 )