使用size_t来移动vector index安全吗?
Is it safe to use size_t to shift vector index?
我更喜欢使用size_t来处理向量索引。但当转移指数时,安全吗?例如,
size_t n = 10000000;
vector<int> v(n);
size_t i = 500000;
size_t shift = 20000;
int a = v(i - (-1) * shift); // Is this ok? what is `(-1) * shift` type, size_t?
int b = v(-shift + i); // Is this ok? what is `-shift` type, size_t?
unsigned
数量为无效操作。c++ 11第5.3.2节:
无符号数的负数是通过减去它来计算的2^n的值,其中n是升序的位数操作数。结果的类型为提升操作数的类型。
所以,这是"安全的",因为这是定义行为。
将size_t
与(-1)
相乘是安全的,它将size_t
的最大值包裹起来,因为size_t
是无符号类型。所以(-1) * shift
和std::numeric_limits<size_t>::max-shift+1
是一样的
当然,你指的是v[...]
而不是v()
;std::vector
没有operator(int)
。
总之,根据经验,
#include <iostream>
using namespace std;
int main(){
unsigned foo = 1;
cout<<(-1)*foo<<'n';
cout<<-foo<<'n';
cout<<foo*(-1)<<'n';
cout<<static_cast<int>(-foo)<<'n';
cout<<static_cast<int>(foo)*-1<<'n';
}
收益率:
4294967295
4294967295
4294967295
-1
-1
因此,一个反的unsigned或一个unsigned乘以-1通过环绕其最大值而溢出(这也应该是理论上的行为)。
对于将size_t传递给http://en.cppreference.com/w/cpp/container/vector/operator_at,如果碰巧std::vector<T>::size_type
不是size_t
(不太可能但可能),在你的向量的size()
的边界内传递size_t
应该是安全的,不会导致UB,因为size_t
必须足够大,以索引任何大小的数组。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 从不同线程使用int64的不同字节安全吗
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 虚拟决赛作为安全
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何将元素添加到数组的线程安全函数?
- C++中的线程安全删除
- 通过网络、跨平台传递std::变体是否安全
- 在std::thread中,joinable()然后join()线程安全吗
- 使用std::istream::peek()总是安全的吗
- 从值小于256的uint16到uint8的Endian安全转换
- 在c++队列中使用pop和visit实现线程安全
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- DrawIndexedInstanced 具有不同的 Index Count per Instance (Directx
- 全局变量 多读取器 一个写入器多线程安全?
- 安全到标准:移动会员?
- AcquireCredentialsHandleA() 返回 PFX 文件的0x8009030e(安全包中没有可用的凭据
- opencv::flann:Index knnsearch线程安全吗?
- 使用size_t来移动vector index安全吗?