我想清除我的代碼下面的內存泄漏。我把它清理乾淨並將其簡化爲最簡單的形式。我不斷從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 []時,某些編譯器不支持調用數組中對象的每個析構函數。因此,不得不調用每個析構函數來釋放內存。 –