2

Possible Duplicate:
Why does the use of ‘new’ cause memory leaks?

What is the difference between (if there is one):

   Player player=*(new Player()); 

and:

   Player &player=*(new Player());

Both (seem to) behave the same way, but I surely miss something?!?

Community
  • 1
  • 1
mipesom
  • 23
  • 2

2 Answers2

4

The difference is that the first makes a copy, whereas the second creates a reference to the object pointed to by the pointer returned by new Player().

Player player=*(new Player()); 

copy-initializes player using the copy-constructor.

Player &player=*(new Player());

just creates an alias for *(new Player()), which is valid because new Player() isn't a temporary. Player& player = Player() would be illegal because of that.

They're the same in that they both suck.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

new Player() is an expression that creates an object (unnamed) on the so-called heap. The result of the expression is a pointer to the newly created object. Now when you do

Player player = *(new Player())

you define a variable named player that is a copy of the newly created object. Moreover, you've lost all handles (access) to the heap object, and you can never free the memory it occupies.

On the other hand,

Player &player=*(new Player());

creates a reference named player to the newly created object. Thus, you have access to that object. In particular, you can free the memory and destroy that object by

delete &player;
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434