C ++ Passing a copy of an object or passing a pointer to an object?

Here is the constructor for my Game class:

// Construct a Game to be played with player on a copy of the board b.
Game(const Board& b, Player* player)
{
  ...
}

This is how I use the constructor:

Player p("Player Name");
Board b(6,3);
Game g(b, &p);

How it works? Is b copied?

If I want to keep a pointer to the player, should I create a private ivar as shown below:

private:
  Player* _player;

...
// In Game constructor
_player = player;
+3
source share
3 answers

If you follow the link or index, a copy will not be made. If you want to save the pointer, then yes, you need to save it somewhere.

Note that it is usually better to use constructor initialization lists rather than assignment. prefer:

Game( const Board& b, Player * player ) : _player( player )
{
    // do something with Board
}

in

Game( const Board& b, Player * player )
{
    _player = player;
    // do something with Board
}

, .

+6

, .
.

. ? , .

. , .

Game(const Board& board, Player& player):
    _player(player)    
{
  ...
}

private:
  Player& _player;

, , , . "" .

private:
    const Board& _board;

Game(const Board& board, Player& player):
    _board(board),
    _player(player)
{
  ...
}
+5

reference, , .

:

Board _privateBoard = b;

b. .

, , -, .

+2
source

Source: https://habr.com/ru/post/1708471/


All Articles