gpt4 book ai didi

c - 深度嵌套结构不好吗?

转载 作者:行者123 更新时间:2023-11-30 20:03:33 24 4
gpt4 key购买 nike

例如

 struct {
struct {
struct {
struct {
int a;
int b;
} AA;
struct {
char *a;
int b;
} BB;
} AAA;
int c;
} DDD;
char *a;
} XX;

事实上,最深的结构体有 8 个嵌套结构体。

我更喜欢 a.b.c.d.e 而不是 a.b.c_d_e

有什么陷阱吗?

最佳答案

从性能的角度来看,子结构的分离可能会增加“父”结构中浪费的空间,因为对齐和填充要求必须针对每个子结构单独评估,而不是全局评估(除非编译器可以证明没有布局兼容的 struct 周围可用于给这些子成员起别名)。

示例:

struct Nested {
int a;
struct {
int c;
double d;
} b;
};

在大多数常见的现代机器上都会像这样放置在内存中

0x00 a
0x04 (padding)
0x08 b.c
0x0c (padding)
0x10 b.d
Total: 0x18 bytes

而等效的“扁平化”结构

struct Flattened {
int a;
int c;
double d;
};

将使其所有成员都是连续的。

0x00 a
0x04 c
0x08 d
Total: 0x10 bytes
<小时/>

这几乎是我能想到的唯一性能缺陷。实际评估的最重要的是可用性成本。深度嵌套的子结构通常使用起来更加冗长,因此您应该反射(reflection)为什么要这样做以及它是否真的值得。

这些实体是独立存在的,没有主体结构吗?例如,您的客户端代码可能想要复制(或指向)其中之一?然后从父结构中取出它们的定义并给它们一个名称。这是通常的情况,我认为根据需要嵌套实例没有问题 - 这就是当您进行 OOP 时实际发生的情况。另请注意,如果您在每个结构中都有要初始化的指针和内容,您可能应该提供一些函数来执行此操作(与 OO 语言中使用构造函数的方式类似),以避免到处重复繁琐的代码。

您是否需要以某种方式利用事实结构中的事实 - 例如,您有一个由它们组成的数组作为成员(或者,在 C++ 中,您希望利用复制构造函数的自动定义来实现大多数情况)你的成员)?那么你可能没问题,尽管同样,不导出明确的名称对你的客户来说是邪恶的(如果他们想要一个指向这些对象之一的指针来节省一些打字怎么办?)。

您是否在(标记的)union 中使用它们作为“替代事件类型”?这是一个合法的用例 - 尽管只是第一级!

你只是为了分组而分组吗?然后三思而后行,you may be falling in a similar trap as what happens sometimes with (C++) namespaces :

Why can we not take advantage of our patient’s mania for hierarchy? Can we not encourage them to write code like this:

namespace MyLibrary {
namespace Useful {
namespace Utility {
int f();
}
namespace Business {
int f();
namespace Utility {
int f();
}
}
}
}

It turns out that almost no encouragement is needed. Humans apparently actually like writing stuff like this:

MyLibrary::Useful::Business::Utility::f();

and when they have done so seem to think they have done something profound. The thought of naming the functions so that their own names are distinct seems repellent to them. And even when the names are distinct, and there is absolutely no reason to use these ludicrous constructs, they will still embrace them as they would long-lost lovers.

过度分类的东西被高估了。

关于c - 深度嵌套结构不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49484809/

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