Ownership with a physical representation

一个人想着一个人 提交于 2019-12-02 06:46:35

C++ ownership essentially boils down to "who is responsible for deleting this particular object were they to die at this particular moment". In your example, as all objects have automatic lifetime, all of them are owned by Process::run itself. There's no ownership transfer involved in any of add, acquire or release.

Now, what about the same thing with dynamic-lifetime objects? Your description (where I assume by C you mean Scene) can be implemented in two different ways still:

  • Scene holds std::unique_ptrs to A's, that's a given
  • Scene and A can hold either std::unique_ptrs or std::shared_ptrs to B.

The choice in the second bullet can be made through the definition of ownership I outlined above. What happens when and A dies while holding a B?

  • If the B should die as well, then A is its sole owner and should hold it via std::unique_ptr
  • If the B should remain inside the Scene, then Scene and A are both owners, and should both hold the B through a std::shared_ptr

This doesn't include non-owning (raw) pointers, which can be useful (for example, if A owns a B but Scene still needs a direct reference for whatever purpose). These must be updated separately.

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