以下のコードからメモリリークを取り除きたいと思います。私はそれをきれいにして、それを最も単純な形にしました。私は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 []を使用している間は配列内のオブジェクトの各消滅者を呼び出すことをサポートしていません。したがって、残念ながらメモリを解放するためには、それぞれのデストラクタを呼び出さなければなりません。 –