简体   繁体   English

size_t的值无效

[英]Invalid Value for size_t

What do people use to denote that size_t is invalid? 人们用什么来表示size_t无效? -1 does not work, and 0 can be a valid size. -1不起作用,0可以是有效大小。

Perhaps ((size_t)-1) ? 也许((size_t)-1)

Strictly speaking, it is a valid size, but once you have this one you're not likely to need any other ;-) 严格来说,这一个有效的大小,但一旦你有这个,你不可能需要任何其他;-)

If you're talking about std::string, then size_t's invalid value is std::string::npos. 如果你在谈论std :: string,那么size_t的无效值是std :: string :: npos。 Normally you shouldn't use -1 because a size_t is unsigned, and you can get failed comparisons on a compiler doing implicit conversions between types. 通常,您不应该使用-1,因为size_t是无符号的,并且您可以在编译器之间进行类型之间的隐式转换时进行失败的比较。

That being said, std::strings's npos is set to 0XFFFFFFFFFFFFFFFF... which is the binary equivallent of -1. 话虽这么说,std :: strings的npos设置为0XFFFFFFFFFFFFFFFF ...这是-1的二进制等值。 It also evaluates to the maximum allowed value for an unsigned size_t field. 它还会计算无符号size_t字段的最大允许值。

Basically you can not. 基本上你不能。 Whatever value you use might be a valid one. 无论您使用什么价值都可能是有效的。 Better pass a flag saying that it is invalid. 最好传递一个标志,说它无效。

And what do you do to denote that an int is invalid? 你怎么做才能表示int无效? -1 is a valid value for an int. -1是int的有效值。 These types don't have designated "invalid" values. 这些类型没有指定“无效”值。 You can decide to choose a certain value (that can never normally be the value of what your variable represents) to represent an illegal value, but that is your own definition, and not something that people generally use. 您可以决定选择某个值(通常永远不会是您的变量所代表的值)来表示非法值,但这是您自己的定义,而不是人们通常使用的定义。

Personally, I don't like this way. 就个人而言,我不喜欢这种方式。 I prefer to create another variable, bool IsValid , which will say, whether the value of that size_t variable is valid. 我更喜欢创建另一个变量bool IsValid ,它将说明该size_t变量的值是否有效。 Sometimes, it may even be better to create a class to encapsulate them. 有时,创建一个类来封装它们甚至可能更好。

My version is: 我的版本是:

#include <limits>
#define invalid_index std::numeric_limits<size_t>::max()

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

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