C++ C++;在我将结构的内存归零后,如何使用它?

C++ C++;在我将结构的内存归零后,如何使用它?,c++,memory,struct,C++,Memory,Struct,你好,当我把结构调零的时候 struct hudelem_color{ byte r, g, b, a; }; 我不能再使用它了,如果我想在使用后再使用它,我会怎么做 ZeroMemory(&hudelem\u color,hudelem\u color的大小)当然,去做吧。你完全可以重复使用它。在ZeroMemory之后,你得到了一个hudelem_颜色,r、g、b和a都为零。就用它吧 一些在重用数千个小对象时需要高性能的代码使用了一种称为“对象池”的模式,google提供了更多信息…和您的

你好,当我把结构调零的时候

struct hudelem_color{ byte r, g, b, a; };
我不能再使用它了,如果我想在使用后再使用它,我会怎么做


ZeroMemory(&hudelem\u color,hudelem\u color的大小)

当然,去做吧。你完全可以重复使用它。在ZeroMemory之后,你得到了一个hudelem_颜色,r、g、b和a都为零。就用它吧


一些在重用数千个小对象时需要高性能的代码使用了一种称为“对象池”的模式,google提供了更多信息…

和您的示例结构

struct hudelem_color{ byte r, g, b, a; };
然后你就可以有这个循环

bool game_continue = true;

while (game_continue)
{
    hudelem_color color;
    memset(&color, 0, sizeof(color));

    // Use the `color` variable, do whatever you want with it
}
循环的每次迭代定义一个新的结构实例,并将其内存归零。这并不是严格地重用结构实例,因为循环中的每次迭代都会创建一个新实例

你也可以

hudelem_color color;

while (game_continue)
{
    memset(&color, 0, sizeof(color));

    // Use the `color` variable, do whatever you want with it
}
上述循环的工作原理与前一个循环几乎相同,但不是创建新实例,而是在循环之前创建每个迭代,然后在每个迭代中实际重用

不过,我个人会推荐第一种变体。如果您这样做了,为什么不简单地添加一个清除字段的默认构造函数,那么您就不必每次迭代都手动执行此操作:

struct hudelem_color
{
    byte r, g, b, a;

    hudelem_color() : r(0), g(0), b(0), a(0) {}
};

// ...

while (game_continue)
{
    hudelem_color color;

    // Here all fields of the structure variable `color` will be zero
    // Use the structure as you see fit
}

hudelem_颜色是一个结构/类型,您需要为它定义一个对象

hudelem_color clr;
ZeroMemory(&clr, sizeof (hudelem_color));

记忆结构定义是没有意义的。

你说“不能再使用它”是什么意思?请提供可能的错误消息和更完整的代码。哦,您确实有一个名为
hudelem\u color
的变量?设置POD类型没有错,所以我看不出您的问题。好的。因此,当我回到游戏中释放结构内存时,我想再次使用该结构。我不确定POD是什么意思。这是一种安全的方法吗,因为我对结构有点怀疑loop@Konroi你说的“安全之路”是什么意思?如果循环中的第一个(或最后一个)语句是将结构归零,那么循环的其余部分将有一个归零的结构。谢谢:)但只需编写
hudelem_color clr{0}
就更简单了;