C++ Object without new

前端 未结 4 1093
礼貌的吻别
礼貌的吻别 2020-12-07 08:31

this is a really simple question but I havn\'t done c++ properly for years and so I\'m a little baffled by this. Also, it\'s not the easiest thing (for me at least) to look

4条回答
  •  余生分开走
    2020-12-07 09:08

    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 deletes it.

提交回复
热议问题