简体   繁体   English

如何安全地将 ssize_t 与 int64_t 进行比较

[英]How to safely compare a ssize_t with a int64_t

I want to safely compare a ssize_t variable with int64_t variable to check if the values are equal.我想安全地将ssize_t变量与int64_t变量进行比较以检查值是否相等。 By safe I mean the comparison should work for any value of ssize_t .安全我的意思是比较应该适用于ssize_t任何值。 My first guess is to use a static_cast to convert the ssize_t to int64_t but I'm not sure if it is a safe way to convert?我的第一个猜测是使用static_castssize_t转换为int64_t但我不确定这是否是一种安全的转换方式?

Something like:就像是:

ssize_t a = read(...);
int64_t b = getsize(...);
if(static_cast<int64_t>(a) == b){
  // ... read succeeded
} else{
  // ... partial or read failure
}

Update: On Ubuntu, they both are of exactly the same size更新:在 Ubuntu 上,它们的大小完全相同

Don't over-complicate things.不要把事情复杂化。

ssize_t and int64_t are both signed types, thus the common type is the bigger of the two, meaning the conversion is value-preserving. ssize_tint64_t都是有符号类型,因此公共类型是两者中较大的一个,这意味着转换是保值的。
In conclusion, directly using the comparison-operator will do the right thing .总之,直接使用比较运算符会做正确的事情

You only have to take care when mixing signed and unsigned, with the unsigned being at least as big as int and the signed type.您只需要在混合有符号和无符号时注意,无符号至少与int和有符号类型一样大。 Because only in that case conversion to the common type won't be value-preserving for negative values.因为只有在这种情况下,转换为普通类型才不会为负值保值。
In that case, C++20 helps with intcmp在这种情况下,C++20 有助于intcmp

In C++20 you don't even need to care about signness or the size of the operands, just use intcmp to do the comparison在 C++20 中,您甚至不需要关心符号或操作数的大小,只需使用intcmp进行比较

if (std::cmp_equal(a, b)) {
  // ... read succeeded
} else{
  // ... partial or read failure
}

There's also std::in_range to check values regardless of type and signness无论类型和符号如何,还有std::in_range来检查值

most of the time you don't have ssize_t .大多数时候你没有ssize_t and when you do what stops you from doing当你做阻止你做的事情时

int64_t a;
ssize_t b;
b = sizeof(ssize_t) == sizeof(int64_t) ? a : whatever_else;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM