Function that creates pointers to classes

If you really want to use raw pointers for your players, you can modify your createPointer function to return what it has created:

player* createPointer()
{
    player* createdPlayer = new player("George");
    // Do whatever you need for initialization!
    return createdPlayer;
}

Then, in the code that wants to use such players, do something like:

//...
player* player1 = createPointer();
player* player2 = createPointer();
//...

Then, when you've done with the players, you can just delete each one...

delete player1;
delete player2;

A better solution (IMHO) would be to put whatever code you (eventually) have in createPointer into the constructor definition for the player class; then you can just use code like player *p1 = new player("Harold"); rather than calling a function each time you make a new player.

But, as mentioned in the comments, you would be better off using either std::vector or std::shared_ptr objects.


You probably need a container of player instances. The default container is std::vector.

Something like

std::vector<player> players;

players.emplace_back("George"); // Create the first player
players.emplace_back("Fred"); // Create the next player
// etc.

You can refer to players by their (0 based) position in players

players[0].do_stuff(); // George does stuff

You can loop over all the players

for (auto & player : players) {
    player.take_turn(); // each player in turn does something
}

When players is destroyed, it automatically cleans up the player objects


If i understand you correctly,maybe there are two solutions to solve your problem. Here the codes.

#include <string>
#include <iostream>
using namespace std;


class Player
{
public:
    Player(string name) :m_name(name) {
        cout << "player " << m_name << " is created\n";
    }
    ~Player()
    {
        cout << "pluaer " << m_name << " is destoryed\n";
    }
private:
    string m_name;
};

//The first solution : return a pointer
Player* creatPlayer_1(const string& name)
{
    return new Player(name);
}

//The second solution : pass a reference of the pointer as the argument
void createPlayer_2(Player*& pPlayer, const string& name)
{
    pPlayer = new Player(name);
}

int main()
{
    Player* pPlayer_one = creatPlayer_1("one");

    Player* pPlayer_two = nullptr;
    createPlayer_2(pPlayer_two, "two");

    delete pPlayer_one;
    delete pPlayer_two;
}

Tags:

C++

Pointers