解除分配向量元素占用的内存的 C++ 问题 [英] C++ trouble with deallocating memory taken by vector elements

查看:30
本文介绍了解除分配向量元素占用的内存的 C++ 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以问题是,当我尝试将非动态 obj 推送到 playerList 或尝试删除 n 时,我得到了段错误(核心转储).我认为问题是在 Helper 类被销毁时引起的,因此向量也被销毁,因此它试图销毁不再存在的对象本身.但是,当我使用 playerList.clear() 时,问题仍然存在.我想我可以用 ~Helper() 销毁 playerList() 中的对象.但我想知道为什么我不能使用非动态对象,而是在 Run() 结束时将它们从 playerList 中清除.

So the problem is that when i try to push non-dynamic obj to playerList or when I try to delete n I get segfault (core dump). I assume that the problem is caused when Helper class is being destroyed so the vector also is being destroyed so it tries to destroy object in itself which does not exist anymore. However when i use playerList.clear() the problem still exist. I think i could just destroy objects in playerList() with ~Helper(). But I would like to know why i cannot use non-dynamic objects and just clear them out of playerList at the end of Run().

class Helper{
public:

    void Run();


private:
    std::vector<Player>playerList;
    ...
};

这就是 Run() 的样子:

that's how Run() looks like:

using namespace std;

void Helper::Run(){
    Player *n = new Player();
    playerList.push_back(*n); //Yup. There is a memleak
}

还有玩家.h:

class Player{
public:

    ...
    ~Player();

private:
    ...
    IClass* typeOfClass = new Warrior();
};

和~玩家:

Player::~Player(){
    delete typeOfClass;
}

和战士(对问题没有影响)

and Warrior (has no effect on the problem)

class Warrior {
public:

    int GetMeleeAttack();
    int GetRangedAttack();
    int GetMagicAttack();
    int AgilityAction();
    int StrengthAction();
    int IntelligenceAction();
    void WhoAmI();

private:

};

Warrior 的方法只返回一些整数.

Warrior's methods just returns some integers.

推荐答案

std::vector<Player>playerList;

应该是

std::vector<Player*>playerList;

如果你想动态分配它们.另一种方法是放置每个元素而不是使用新元素.

if you want to allocate them dynamically. The other method would be to emplace each element and not use new.

当使用 new 时,你是在堆上分配,但你是通过传递堆上分配的值在向量中创建一个新元素.而且你有一个悬空指针(内存泄漏)

When using new you are allocating on the heap but you are creating a new element in the vector by passing the value from the one allocated on heap. And you have a dangling pointer ( memory leak )

如果您使用的是指针向量,请记住在销毁向量时释放所有元素.

Remember to deallocate all the elements at the destruction of the vector if you are using a vector of pointers.

另一种方法是:

 std::vector<std::unique_ptr<Player> >playerList;

这将解决分配问题.

这篇关于解除分配向量元素占用的内存的 C++ 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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