在size_t中使用负整数是否安全? [英] Is it safe to use negative integers with size_t?

查看:125
本文介绍了在size_t中使用负整数是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看到了一些这样的C ++代码.它使用条件来决定是通过std::vector向前还是向后走.编译器没有抱怨,但是我认为size_t是未签名的.这很危险吗?

I just saw some C++ code like this. It was using a condition to decide whether to walk forward or backward through a std::vector. The compiler doesn't complain, but I thought size_t was unsigned. Is this dangerous?

vector<int> v { 1,2,3,4,5 };    
bool rev = true;

size_t start, end, di;
if (rev) {
    start = v.size()-1;
    end = -1;
    di = -1;
}
else {
    start = 0;
    end = v.size();
    di = 1;
}

for (auto i=start; i!=end; i+=di) {
    cout << v[i] << endl;
}

推荐答案

使用无符号整数(并且size_t是无符号)的定义很明确,并且具有环绕效果:该行为由标准保证,而不是与带符号的整数,这是标准所不能保证的.

It's well defined to use unsigned integers (and size_t is unsigned) this way, with wraparound: that behavior is guaranteed by the standard, as opposed to with signed integers, where it's not guaranteed by the standard.

但是它不必要地聪明.

作为一般规则,为避免因将促销内容隐式包装为无符号而引起的问题,请对位级内容使用无符号整数,对数字使用有符号整数.在需要与size_t相对应的有符号整数的地方,您可以找到ptrdiff_t.定义一个带有签名结果的n_items函数,例如

As a general rule, to avoid problems due to implicit wrapping promotions to unsigned, use unsigned integers for bit-level stuff, use signed integers for numbers. Where you need a signed integer corresponding to size_t there's ptrdiff_t for you. Define an n_items function with signed result, e.g.

using Size = ptrdiff_t;

template< class Container >
auto n_items( Container const& c )
    -> Size
{ return end( c ) - begin( c ); }

您就可以开始使用了,编译器不再发出任何愚蠢的警告.

and you're set to go, no more sillywarnings from the compiler.

不是给定的代码太聪明

vector<int> v { 1,2,3,4,5 };    
bool rev = true;

size_t start, end, di;
if (rev) {
    start = v.size()-1;
    end = -1;
    di = -1;
}
else {
    start = 0;
    end = v.size();
    di = 1;
}

for (auto i=start; i!=end; i+=di) {
    cout << v[i] << endl;

例如.

const vector<int> v { 1,2,3,4,5 };    
const bool reverse = true;  // whatever

for( int i = 0; i < n_items( v );  ++i )
{
    const int j = (reverse? n_items( v ) - i - 1 : i);
    cout << v[j] << endl;
}

这篇关于在size_t中使用负整数是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆