I just spent the past few hours reading about smart pointers and I'm trying to implement them into some of my projects to replace regular old pointers.
In one of my projects I have a class Player along with a vector of pointers to objects of type 'Player':
std::vector<Player*> players
. The program is a Texas Hold'em poker application where players can join a LAN game. Since clients may connect or disconnect at any time (if I'm the host), I used a vector of type <Player*> so I can use
new Player
and
delete Player
to allocate and deallocate memory accordingly. When the program is run, a Player is constructed immediately for that machine. Before I tried implementing smart pointers, I could easily copy this players address into
std::vector<Player*> players
. This instance of Player is created at the start of the program and remains alive until the program ends.
1 2 3 4 5 6 7 8 9 10
|
int main(){
Player player;
std::vector<Player*> players;
players.push_back(&player); //the address of 'player' is pushed into a vector of pointers that point to objects of type 'Player'
while(true){
//execute the game here...
}
}
|
The above code works fine, but what from I've read, it sounds like using a shared_ptr is preferred because it prevents memory leaks and dangling pointers. Is it a good idea to replace my old pointers with smart pointers in this scenario and if so, how I can implement it? Below are a couple attempts of what I've tried:
1 2 3 4 5 6 7 8
|
int main(){
Player player;
std::vector<std::shared_ptr<Player>> players;
players.push_back(&player); //I know this won't work because &player is not of type std::shared_ptr<Player>
players.push_back(std::make_shared<Player> &player); //Intuitively I feel like this on the right track, but im not quite there.
}
|
I thought about dynamically allocating
player
, but since that instance should remain alive the duration of the program, I don't see why I should have to create it dynamically.
Could someone point me in the right direction?