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 AddRef
ed) --- 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 nsCOMPtr
s 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论