Can an object destroy itself?

好久不见. 提交于 2019-12-04 00:11:01

Yes, it's legal to call delete this from inside a member function. But there's very rarely a good reason to do so (especially if you're writing idiomatic C++ where most memory-management tasks should be delegated to containers, smart pointers, etc.).

And you need to be very careful:

  • the suicide object must have been allocated dynamically via new (not new[]).
  • once an object has committed suicide, it is undefined behaviour for it to do anything that relies on its own existence (it can no longer access its own member variables, call its own virtual functions, etc.).

Yes, it should work. Even delete this; is allowed.

But the code calling specialMoves() could be in for a nasty surprise.

Q: Can an object destroy itself?

A: Sure. "delete this" is a popular idiom in COM/ActiveX

As far as your algorithm, I'd suggest:

  • a "board" object has "tiles". Perhaps just a simple 2-D array.

  • You start out with n "pieces"

  • Some controller (perhaps a "game" object), moves a "piece" with respect to a "tile".

  • Each "tile" has a reference to 0 or 1 "pieces"

I'm not sure I see any reason to create or delete anything on a per-move basis.

IMHO...

As long as you don't access member variables or the this pointer after the call to destroy the object, you should be fine. Since it doesn't appear you're doing either of these things, the example should work.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!