在C ++代码中将size_t变量与-1(最大大小值)进行比较 [英] Comparison size_t variable with -1 (maximum size value) in c++ code
问题描述
我正在重构一个库,并试图摆脱许多gcc警告.这些警告的大部分与有符号/无符号比较有关,并且与 size_t
的用法有关.该库可在64位Linux系统上使用.
程序员使用-1作为特殊值,类似于 std :: string :: npos
.库中很多地方的代码如下所示:
class AnnotationBase{上市:size_t m_offset = -1;size_t m_length = -1;}...AnnotationBase foo(const std :: string& text,const AnnotationBase& annot){AnnotationBase newAnnot;//做一些注释和文字...if(newAnnot.m_offset == -1){//做其他工作...}返回newAnnot;}
问题在于,由于有符号/无符号比较,gcc在 if(newAnnot.m_offset == -1)
行上生成了警告:
警告:有符号和无符号整数表达式[-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> ::最大限度();}
(创建新常量会在不同的库和名称空间中产生许多类似的常量,例如 libling :: NONE
, libother :: UNKNOWN
, liblongnamesapcename ::什么
)?
您可以执行 std :: string
的操作,并定义 static const size_t AnnotationBase :: npos = -1
.然后将其用作比较.我不会认为每个库都有一个常数是一个问题,但是如果要避免这种情况,可以直接使用 std :: string :: npos
(尽管这样会使代码更严格).>
I'm refactoring a library and trying to get rid of many gcc warnings. The big part of these warning are about signed / unsigned comparison and are related to the usage of size_t
. The library works on 64 bit Linux systems.
A programmer used -1 as the special value similar to std::string::npos
.
There are many places in the library where code looks like this:
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;
}
The problem lies in the warning that gcc generates on the line if(newAnnot.m_offset == -1)
because of a signed / unsigned comparison:
"warning: comparison between signed and unsigned integer expressions [-Wsign-compare]"
What is the proper way to compare size_t
variable in C++ with the maximum value (-1) without warning? Doing this like if(newAnnot.m_offset == std::numeric_limits<size_t>::max())
is very inconvenient due to complexity and length of this expression.
Is it a good way to use C-style defined value SIZE_MAX
or it is better to create own constant like namesapce libling { const NONE = std::numeric_limits<size_t>::max(); }
(Creating new constant leads to many similar constants in different libraries and namespaces like libling::NONE
, libother::UNKNOWN
, liblongnamesapcename::NOTHING
)?
You could do what std::string
does and define a static const size_t AnnotationBase::npos = -1
. Then use that in comparisons as a convention. I wouldn't consider one constant per library a problem, but if you want to avoid that, you can use std::string::npos
directly (that makes the code more rigid though).
这篇关于在C ++代码中将size_t变量与-1(最大大小值)进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!