C++ Object without new

前端 未结 4 1070
礼貌的吻别
礼貌的吻别 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:01

    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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 09:13

    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);
    
    0 讨论(0)
  • 2020-12-07 09:19

    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.

    0 讨论(0)
提交回复
热议问题