简体   繁体   English

隐式转换为 size_t?

[英]Implicit cast to size_t?

I want to know - does C++ do implicit cast when we initialize unsigned size_t with some value?我想知道 - 当我们用某个值初始化 unsigned size_t 时,C++ 会进行隐式转换吗? Like this:像这样:

size_t value = 100;

And does it make sense to add 'u' literal to the value to prevent this cast, like this?将“u”字面值添加到值中以防止这种转换是否有意义,就像这样?

size_t value = 100u;

does C++ do implicit cast when we initialize unsigned size_t with some value?当我们用某个值初始化 unsigned size_t 时,C++ 会进行隐式转换吗? Like this:像这样:

 size_t value = 100;

Yes.是的。 std::size_t is an (alias of an) integer type. std::size_t是一个(别名)integer 类型。 An integer type can be implicitly converted to all other integer types. integer 类型可以隐式转换为所有其他 integer 类型。

And does it make sense to add 'u' literal to the value to prevent this cast, like this?将“u”字面值添加到值中以防止这种转换是否有意义,就像这样?

There is still likely an implicit conversion with the u literal suffix since std::size_t is not necessarily (nor typically) unsigned int .由于std::size_t不一定(也不通常) unsigned int ,因此仍然可能存在带有u文字后缀的隐式转换。 It may be for example unsigned long int or unsigned long long int .例如,它可能是unsigned long intunsigned long long int There is a standard proposal to add integer literal for the std::size_t alias, but there doesn't exist one for now.有一个标准建议为std::size_t别名添加 integer 文字,但目前不存在。

Using a matching literal doesn't matter much in this example, as long as the type of the literal can represent the value in question, and as long as the literal value doesn't exceed the bounds of the initialised type.在此示例中,使用匹配的文字并不重要,只要文字的类型可以表示所讨论的值,并且只要文字值不超过初始化类型的范围即可。 Even the smallest integer types can represent 100. The choice is largely a matter of taste.即使是最小的 integer 类型也可以表示 100。选择在很大程度上取决于品味。


Note that "implicit cast" is a contradiction in terms.请注意,“隐式转换”在术语上是矛盾的。 Cast is an explicit conversion. Cast 是一种显式转换。

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

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