gpt4 book ai didi

C++ - 使用 vector 清理堆上类的正确方法

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:16 25 4
gpt4 key购买 nike

我有这门课:

class GameData
{
public:
GameData();
~GameData();
vector<Bullet> bullets;
}

在主程序中,我创建了一个 GameData 指针并使用 new 为其分配内存。我知道新的,你也应该删除数据。我上面的 vector 不是指向 Bullets 的指针的 vector ,只是 Bullets 本身(它们应该是指针吗?)在 ~GameData() 函数中,我需要什么来清理子弹?我应该确保它是空的,如果不清除它吗?为了良好的内存管理,正确“删除”它的具体方法是什么。如果我的设计有误,请告诉我正确的处理方式。

谢谢

最佳答案

In the ~GameData() function, what do I need to cleanup bullets?

没有。它由将自动调用的 vector 的析构函数完成。

-

I create a GameData pointer and allocate memory for it with new. I know with new, you should have to delete the data as well

如果您使用某种形式的智能指针,例如 std::unique_ptrstd::shared_ptr,则不必这样做。使用智能指针,您不必删除它,因为这是智能指针本身的责任。

从这里阅读智能指针部分:

关于C++ - 使用 vector 清理堆上类的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10241364/

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