XPCOM ownership guidelines 编辑

If you made it, you own it.

...naturally. If you create a temporary object, obviously it's up to you to destroy it. That's a sure sign of ownership. If you create an object with a longer lifespan, you will own it until you give ownership away.

All "factory" and "getter" functions produce owning pointers.

Such a function is the perfect example of something that creates an object with a longer lifespan that itself, and gives away ownership (by producing a pointer that is already AddRefed) --- in this case, to the caller. This is terrific for factory functions, but can be problematic for mere getters. It's unfortunate if you just needed access to it for a moment. In the latter case, caching the pointer you got back makes you a de facto owner. This may not be appropriate; and it may be hard to remedy without knowing if the object in question was truly created in response to your query.

Needing it isn't, by itself, a valid reason for owning it.

You don't own an object because you need it. In fact often you own it because it needs you.

If you own it, it shouldn't own you.

Even transitively. Or put another way: the ownership graph for any system should be acyclic. Anytime there is a cycle of ownership, there is a situation that isn't automatically handled by destructors. Special code must be provided and called to break the cycle before the participants can be individually released.

You don't need to own it if it's lifetime is guaranteed to be longer than yours.

As for instance, when it owns you.

Parents own their children (and not the reverse).

Though parents may not need to own their children. For instance, a tree may own all the nodes that are in it. All the nodes in the tree point to each other with non-owning pointers. In the simplest scheme, however, parents point to their children with owning-pointers, children point back to their parents with non-owning-pointers.

Containers own the things they contain (and not the reverse).

Original Document Information

Use nsCOMPtrs to implement owning-pointers.

It's explicit, efficient, and fairly bullet-proof. It's easier to write `getter's and `setter's; and you don't need to put anything in your destructor.

  • Author: Scott Collins
  • Last Updated Date: May 8, 2003
  • Copyright Information: Copyright© 1999 by Netscape; use is subject to the NPL. Portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:79 次

字数:4544

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文