C++ Object without new
Solution 1:
This expression:
CPlayer(position, attacker)
creates a temporary object of type CPlayer
using the above constructor, then:
CPlayer newPlayer =...;
The mentioned temporary object gets copied using the copy constructor to newPlayer
. A better way is to write the following to avoid temporaries:
CPlayer newPlayer(position, attacker);
Solution 2:
The above constructs a CPlayer object on the stack, hence it doesn't need new
. You only need to use new
if you are trying to allocate a CPlayer object on the heap. If you're using heap allocation, the code would look like this:
CPlayer *newPlayer = new CPlayer(position, attacker);
Notice that in this case we're using a pointer to a CPlayer object that will need to be cleaned up by a matching call to delete
. An object allocated on the stack will be destroyed automatically when it goes out of scope.
Actually it would have been easier and more obvious to write:
CPlayer newPlayer(position, attacker);
A lot of compilers will optimise the version you posted to the above anyway and it's clearer to read.
Solution 3:
CPlayer newPlayer = CPlayer(position, attacker);
This line creates a new local object of type CPlayer. Despite its function-like appearance, this simply calls CPlayer's constructor. No temporaries or copying are involved. The object named newPlayer lives as long as the scope it's enclosed in. You don't use the new
keyword here because C++ isn't Java.
CPlayer* newPlayer = new CPlayer(position, attacker);
This line constructs a CPlayer object on the heap and defines a pointer named newPlayer to point at it. The object lives until someone delete
s it.
Solution 4:
newPlayer is no dynamically allocated variable but an auto, stack-allocated variable:
CPlayer* newPlayer = new CPlayer(pos, attacker);
is different from
CPlayer newPlayer = CPlayer(pos, attacker);
newPlayer is allocated on the stack via the normal CPlayer(position, attacker) constructor invocation, though somewhat verbose than the usual
CPlayer newPlayer(pos, attacker);
It's basically the same as saying:
int i = int(3);