Warning 22.11.1.
It is almost always an error to manually call the destructor. Calling it manually generally means it will run twice, once when called directly and once when it runs automatically, possibly trying to free the same memory twice.
~ClassName();
PlayerList
class with a destructor to clean up the managed array. (Normally we would not print the destructor message in a real program, that is done just for demonstration purposes.)
module;
#include <iostream>
#include <string>
export module PlayerList;
using namespace std;
export class PlayerList {
private:
string* m_players; // pointer to the array of player names
int m_size; // number of players in the list
public:
PlayerList(int size);
~PlayerList(); // Destructor
void setPlayerName(int index, const string& name);
void print() const;
};
PlayerList::PlayerList(int size) {
if (size <= 0) {
throw invalid_argument("Size must be positive");
}
m_size = size;
m_players = new string[m_size]; // allocate memory for the array
}
PlayerList::~PlayerList() {
delete[] m_players; // deallocate memory for the array
cout << "**PlayerList destroyed and memory freed.**" << endl;
}
void PlayerList::setPlayerName(int index, const string& name) {
if (index < 0 || index >= m_size) {
throw out_of_range("Index out of range");
}
m_players[index] = name; // set the player name at the given index
}
void PlayerList::print() const {
cout << "Player List: ";
for (int i = 0; i < m_size; ++i) {
cout << m_players[i] << " ";
}
cout << endl;
}
m_players
. The memory for the PlayerList variables themselves is automatically managed by C++ and does not need to be deleted manually.
m_players
points to needs to be cleaned up in the destructor.PlayerList
object is destroyed at the end of main. And AddressSanitizer should now not identify any leaks.
testPlayerList()
that creates a PlayerList
object. When testPlayerList()
ends, the PlayerList
object is destroyed, and we see the destructor message. testPlayerList()
is called twice from main
, so you will see two destructor messages, one at the end of each function call.
classDiagram class NumberList { -m_numbers : int* -m_size : int -m_description : string }