C ++ object without new

This is a very simple question, but I have not done C ++ for many years for many years, and therefore I am a bit puzzled by this. Also, this is not the easiest thing (at least for me) to search the Internet, rather than try.

Why doesn't this use the new keyword and how does it work?

Basically, what is going on here?

 CPlayer newPlayer = CPlayer(position, attacker); 
+46
c ++ new-operator
Nov 19 '09 at 16:57
source share
4 answers

This expression:

 CPlayer(position, attacker) 

creates a temporary object of type CPlayer using the constructor above, and then:

 CPlayer newPlayer =...; 

The specified temporary object is copied using the copy constructor in newPlayer . It is best to write the following to avoid temporary:

 CPlayer newPlayer(position, attacker); 
+40
Nov 19 '09 at 16:59
source share
β€” -

The above object creates a CPlayer object on the stack, so it does not need new . You need to use new if you are trying to allocate a CPlayer object on the heap. If you use heap distribution, the code will look like this:

 CPlayer *newPlayer = new CPlayer(position, attacker); 

Please note that in this case we use a pointer to the CPlayer object, which will need to be cleared using the appropriate call before delete . An object allocated on the stack will be automatically destroyed when it goes out of scope.

In fact, it would be easier and clearer to write:

 CPlayer newPlayer(position, attacker); 

Many compilers optimize the version you posted above and read more clearly.

+30
Nov 19 '09 at 17:00
source share
 CPlayer newPlayer = CPlayer(position, attacker); 

This line creates a new local object of type CPlayer. Despite its functional appearance, it simply calls the CPlayer constructor. No temporary or copying involved. An object named newPlayer lives until the application area is turned on. You are not using the new keyword here because C ++ is not Java.

 CPlayer* newPlayer = new CPlayer(position, attacker); 

This line creates a CPlayer object on the heap and defines a pointer named newPlayer to point to it. The object lives until it is delete .

+7
Nov 19 '09 at 17:40
source share

newPlayer is not a dynamically allocated variable, but an auto variable assigned by the stack:

 CPlayer* newPlayer = new CPlayer(pos, attacker); 

differs from

 CPlayer newPlayer = CPlayer(pos, attacker); 

newPlayer is allocated on the stack by calling the CPlayer constructor (position, attacking), although it is somewhat more detailed than usual

 CPlayer newPlayer(pos, attacker); 

This is basically the same as saying:

 int i = int(3); 
+4
Nov 19 '09 at 17:07
source share



All Articles