gpt4 book ai didi

c++ - Bool 标志与 Unsigned Char 标志

转载 作者:行者123 更新时间:2023-11-30 03:26:31 28 4
gpt4 key购买 nike

免责声明:如果我在这篇文章中提出任何虚假声明,请纠正我。

考虑一个包含八个 bool 成员变量的结构。

/*
* Struct uses one byte for each flag.
*/
struct WithBools
{
bool f0 = true;
bool f1 = true;
bool f2 = true;
bool f3 = true;
bool f4 = true;
bool f5 = true;
bool f6 = true;
bool f7 = true;
};

分配给每个变量的空间是一个字节长度,如果变量单独用作标志,这似乎是一种浪费。就变量而言,减少这种空间浪费的一种解决方案是将八个标志封装到一个 unsigned char 成员变量中。

/*
* Struct uses a single byte for eight flags; retrieval and
* manipulation of data is achieved through accessor functions.
*/
struct WithoutBools
{
unsigned char getFlag(unsigned index)
{
return flags & (1 << (index % 8));
}
void toggleFlag(unsigned index)
{
flags ^= (1 << (index % 8));
}

private:
unsigned char flags = 0xFF;
};

标志是通过检索和操作的。按位运算符,结构为用户提供了一个接口(interface)来检索和操作标志。虽然标志大小已经减少,但我们现在有两个额外的方法可以增加结构的大小。我不知道如何对这种差异进行基准测试,因此我无法确定上述结构之间是否存在任何波动。

我的问题是:

1) 这两个结构之间的空间差异可以忽略不计吗?

2) 通常,这种通过将 bool 值压缩成单个字节来“优化” bool 值集合的方法是个好主意吗?在嵌入式系统上下文中或其他情况下。

3) C++ 编译器是否会进行这样的优化,在可能和适当的情况下压缩 bool 集合。

最佳答案

we now have the two additional methods that add to the size of the struct

方法是代码,不会增加结构的大小。只有数据构成结构的大小。

3) Would a C++ compiler make such an optimisation that compacts a collection of bools wherever possible and appropriate.

那是响亮的“不”。不允许编译器更改数据类型。

1) Would the difference in space between these two structs be negligible?

不,这两种方法之间肯定存在大小差异。

2) Generally, is this approach of "optimising" a collection of bools by compacting them into a single byte a good idea? Either in an embedded systems context or otherwise.

通常是的,为标志建模的惯用方法是在无符号整数内进行按位操作。根据所需标志的数量,您可以使用 std::uint8_tstd::uint16_t 等。

然而,最常见的建模方法不是像您所做的那样通过索引,而是通过掩码。

关于c++ - Bool 标志与 Unsigned Char 标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48290800/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com