我想清除我的代码下面的内存泄漏。我把它清理干净并将其简化为最简单的形式。我不断从valgrind获取内存泄漏。我想使用一个对象数组来编译一个名称列表,而不是清理内存,所以最后没有泄漏。如果可能的话,我想在main中声明数组。使用删除/删除[]但仍有内存泄漏
//in Player.h
#include <iostream>
#include <string>
#include <string>
#include <cstring>
class Player
{
private:
std::string first, last;
public:
Player();
~Player(); //I tried my code with and without this destructor
Player(std::string first_name, std::string last_name);
};
//in player.cpp
#include "Player.h"
#include <iostream>
#include <string>
#include <cstring>
Player::Player(std::string first_name, std::string last_name)
{
this->first=first_name;
this->last=last_name;
}
Player::~Player()
{ //I tried both commands below separately and I still have memory leaks
//delete [] Player;
//delete [] myPlayer;
}
// in Driver.cpp
#include "Player.h"
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
int main()
{
std::string temp_First, temp_Last;
Player *myPlayer[2];
temp_First="John";
temp_Last="Smith";
myPlayer[0] = new Player(temp_First, temp_Last);
temp_First="Poca";
temp_Last="Hontas";
myPlayer[1] = new Player(temp_First, temp_Last);
delete [] myPlayer;
return 0;
}
你不应该写,需要使用手动'delete'开始与代码。 –
Std :: vector会给你没有新/删除麻烦的需要,所以没有内存泄漏。 – stefaanv
这对数组的整数,双精度等效果都很好。但是在对象数组的情况下,在使用delete []时,某些编译器不支持调用数组中对象的每个析构函数。因此,不得不调用每个析构函数来释放内存。 –