XPCOM 学习笔记 - 引用计数

关于 XPCOM 中引用计数的一段描述:

When a component gets created, an integer inside the component tracks this reference count. The reference count is incremented automatically when the client instantiates the component; over the course of the component’s life, the reference count goes up and down, always staying above zero. At some point, all clients lose interest in the component, the reference count hits zero, and the component deletes itself.

关于引用计数的概念其实并不陌生,以前用过 boost 中的 smart pointer,就是很方便的引用计数装置。但 XPCOM 中的引用计数与其有所不同,boost 的 smart pointer 是在一个独立的模板类当中来实现针对某个对象的引用计数,而 XPCOM 的引用计数则是做在 XPCOM 对象的内部。

这就造成一个问题:当一个对象创建时,会自动给自己的引用计数加一。它带来的最直接的麻烦就是在使用 nsCOMPtr 这个类似于 smart pointer 的类时,当其指向新创建的对象,就不能增加引用计数,而指向已经创建好的对象,则需要增加引用计数。关于这一点,在 nsCOMPtr 的手册中写的比较多了,但对于新手来说,依然比较难以理解。如果 XPCOM 在设计时采用 boost smart pointer 类似的结构,可能编程会容易很多。

最近一段时间看到的引用计数比较多的都是普通的,对于 Weak 的引用计数还没有来得及仔细看,以后有时间看了补上。

发表您的评论

提示:如果你刚刚提交过评论,但是还没有被显示出来,请点击这里刷新一下: 刷新评论