没有新对象的 C + + 对象

这是一个非常简单的问题,但是我已经很多年没有正确地使用 c + + 了,所以我对此有点困惑。另外,在网上查找(至少对我来说)并不是一件容易的事情,不是一件容易的事情。

为什么不使用 new关键字,它是如何工作的?

基本上,这里发生了什么?

CPlayer newPlayer = CPlayer(position, attacker);
55800 次浏览

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);

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.

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);
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.