Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

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

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.

Original Document Information

  • 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.

Document Tags and Contributors

Tags: 
 Contributors to this page: teoli, Mgjbot, Jorend
 Last updated by: Mgjbot,