bool类型变量是如何存储在内存中? (C ++) [英] How a bool type variable is stored in memory? (C++)

查看:1097
本文介绍了bool类型变量是如何存储在内存中? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

布尔测试;

的sizeof(测试)= 1 如果使用VS 2010因为每一个C ++数据类型必须是可寻址的,
测试布尔变量是8位(1字节)。

sizeof(test) = 1 if using VS 2010. Since every C++ data type must be addressable, the "test" bool variable is 8-bits(1 byte).

我的问题是,它的测试变量确实在内存占用1个字节?

My question is that does the "test" variable really occupy 1 byte in memory?

有没有实现的技能,可以使布尔数据类型仅占
一点?如果是的话,你能不能举个例子?

Is there any implementation skill that can make the bool data type occupy only one bit? If yes, can you give me an example?

布尔test1的[32] (2010年VS)
INT测试2 (2010年VS)

bool test1[32](in VS 2010), int test2(in VS 2010)

不要测试1 测试2 占用相同的内存?

Do test1 and test2 occupy the same memory?

推荐答案

测试1 的每个元素都必须是可寻址。这意味着测试1 至少需要32 字节(而不是位)。

Every element of test1 must be addressable. This implies that test1 takes at least 32 bytes (and not bits).

如果你想多个布尔值存储在一个变量,使用和std :: bitset 的std ::矢量<布尔> (但要知道,后者是没有真正的bool的载体,它的设计节省空间的特化)。

If you want multiple boolean values to be stored in a single variable, use std::bitset or std::vector<bool> (but be aware that the latter is not really a vector of bools, it is a specialization designed to save space).

IIRC,C ++ 11还定义的std ::来,dynamic_bitset

IIRC, C++11 also defines std::dynamic_bitset.

这篇关于bool类型变量是如何存储在内存中? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆