【发布时间】:2014-08-02 10:43:54
【问题描述】:
我正在重构一个库并试图摆脱许多 gcc 警告。这些警告的很大一部分是关于有符号/无符号比较的,并且与size_t 的使用有关。该库适用于 64 位 Linux 系统。
程序员使用 -1 作为类似于std::string::npos 的特殊值。
库中有很多地方的代码是这样的:
class AnnotationBase
{
public:
size_t m_offset = -1;
size_t m_length = -1;
}
...
AnnotationBase foo(const std::string& text, const AnnotationBase& annot)
{
AnnotationBase newAnnot;
// do some job with annotations and text
...
if(newAnnot.m_offset == -1)
{
// do some other job
...
}
return newAnnot;
}
问题在于 gcc 在if(newAnnot.m_offset == -1) 行上由于有符号/无符号比较而生成的警告:
"warning: comparison between signed and unsigned integer expressions [-Wsign-compare]"
在没有警告的情况下将 C++ 中的 size_t 变量与最大值 (-1) 进行比较的正确方法是什么?由于这个表达式的复杂性和长度,像if(newAnnot.m_offset == std::numeric_limits<size_t>::max()) 这样的操作非常不方便。
使用 C 风格定义值 SIZE_MAX 是一种好方法,还是更好地创建自己的常量,如 namesapce libling { const NONE = std::numeric_limits<size_t>::max(); }(创建新常量会导致在不同的库和命名空间中出现许多类似的常量,如 libling::NONE、@ 987654331@, liblongnamesapcename::NOTHING)?
【问题讨论】:
-
我当然会使用命名常量,例如
if (newAnnot.m_offset == NoneOffset) ...,然后可以声明为const size_t NoneOffset = -1;,这应该可以解决问题。使用您对NONE的定义也可以。
标签: c++ comparison warnings unsigned-integer size-t