c++ - 是否保证 size_t、vector::size_type 等 typedef 不会绑定(bind)到 char 类型?

标签 c++ char size-t

cstdint typedef 绝对有可能绑定(bind)到 char 变量。例如,很可能uint_least8_t绑定(bind)到unsigned char,而int_least8_t绑定(bind)到signed char

标准是否保证类似的事情不会发生在 size_t 或类似的类型上?或者至少存在这样的类型将绑定(bind)到某些 char 类型(例如 unsigned char 或什至 wchar_t)的纯粹理论上的可能性?

最佳答案

我们所知道的 std::size_t是:

The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.

如果unsigned char满足这个条件,它可以用作std::size_t .

但是,这种担忧纯粹是理论上的,因为没有一个真正的平台(据我所知) unsigned char足够宽了(好吧,那是错误的)一个 char 类型被用作 std::size_t等等。

如果你 super 偏执,你可以将值提升到至少int与一元 + :

std::cout << +vector.size();

即使大小类型是字符类型,这也会打印数字。

对于阅读,您可以使用 std::common_type<unsigned int, std::size_t>::type 类型的变量(可能通过 typedef )然后在 sizeof(int) > sizeof(std::size_t) 的情况下进行边界检查.

关于c++ - 是否保证 size_t、vector::size_type 等 typedef 不会绑定(bind)到 char 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32915434/

相关文章:

c++ - 是什么阻止了编译器对强异常安全代码重新排序的优化?

c++ - 为什么在 C++ 中将 "size_type"变量的地址用作 "stoi()"的参数?

C++ 字符串 size_t

c++ - 调用库时崩溃

c++ - QSqlQuery 行影响结果

c++ - 从二进制文件中读取结构

c++ - 在 ImGui 中嵌入大于字符大小的字体

java - 关于字符变量的增量

python - 如何从正则表达式模式返回随机字符? python 3

C size_t 不在 printf 中打印