Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
    ...
};

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
}

also Player.h:

class Player{
public:

    ...
    ~Player();

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

and ~Player:

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's methods just returns some integers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
131 views
Welcome To Ask or Share your Answers For Others

1 Answer

std::vector<Player>playerList;

should be

std::vector<Player*>playerList;

if you want to allocate them dynamically. The other method would be to emplace each element and not use 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.

Another method would be:

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

That will take care of the allocation issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...