CppUnit 笔记

WebKit的智能指针分析 - Part 1:RefCounted

obi posted @ 2010年10月05日 21:13 in C++ with tags c++ WebKit 指针 , 17210 阅读

 

在WebKit的官网上有一篇使用指南:RefPtr and PassRefPtr Basics,从应用的角度讲解了RefPtr类族的由来,及使用方法。但很无厘头的是,这里面居然没有提到如何创建一个有引用计数功能的类!?(教你如何用砖头造房子却不教你如何造砖头)

在抱怨作者的粗心、懒惰、和恶搞精神后,我只能用一句俗话来安慰自己:还好有源代码,还好有源代码,⋯⋯WebKit我来了!!!

WebKit是个非常优秀的开源项目,应用范围广就不说了(safari、chrome、iphone、android、⋯⋯),代码质量也是高得一塌糊涂:清晰的模块划分、清晰的代码组织架构、晦涩(巧妙的同义词)的C++小技巧等优点完全值得有心提高内功的同志一读。

下面就是我在学习WebKit源代码里的RefPtr智能指针的一些心得。

Overview

WebKit的智能指针由类族 RefPtr 来实现,其核心由三个类组成:

  • RefCounted
  • RefPtr
  • PassRefPtr

其中RefCounted提供了引用计数器(一个int型成员),而RefPtr和PassRefPtr则提供了自动管理引用计数器的功能。根据RefPtr and PassRefPtr Basics的说法,最初并没有RefPtr和PassRefPtr,这两个类是2005年才加入的,在它们出现之前完全是靠找死的人工管理RefCounted的引用计数。RefCounted类本身是没有问题的,但它的使用方法相当繁琐,繁琐到开发人员发现很多内存泄露都是由于对方法ref()和deref()的调用不当而造成一半以上内存泄露的程度。为了简化RefCounted的使用方法,RefPtr诞生了,而为了更高效地传递参数,开发人员又创造了PassRefPtr。

RefCounted

RefCounted的源代码在这里:RefCounted.h

这个文件里定义了两个类:非模板类RefCountedBase和模板类RefCounted,从名字上就能看出来RefCounted继承于RefCountedBase。像维护引用计数器这么简单的活儿只使用一个类就绰绰有余了,这里之所以做成两个类是为了减少template hoisting(实例化模板导致的代码膨胀)。总而言之,最终的RefCounted完成了这样的功能:

  • 定义了成员变量:int m_refCount
  • 定义函数ref
    		// 
    void ref()
    {
        ++m_refCount;
    }
  • 定义函数deref
    		// 
    void deref()
    {
        if (derefBase())
            delete static_cast<T*>(this);
    }
    derefBase的定义是:
    		// 
    // Returns whether the pointer should be freed or not.
    bool derefBase()
    {
        if (m_refCount == 1) {
          return true;
        }
    
        --m_refCount;
        return false;
    }

上面的ref()和deref()就是RefCounted的核心功能了,不过有一点要注意的是RefCounted的析构函数是protected的,这样就不能直接定义RefCounted对象了,而是必须从RefCounted继承子类才能行。但是这里不同于一般的继承,这里玩了个小trick:

class Frame : public RefCounted<Frame> {
  // ...
}

和一般的继承不一样吧,之所以要写成这样的原因在于函数deref()能够删除正确的对象!在函数deref()里,如果计数器到了1,就必须把自己销毁(即delete this),但此时的RefCounted直接来一句delete this是不对的,因为如果有一个类Foo继承于RefCounted,那在RefCounted的成员函数里调用delete this只会触发RefCounted的析构函数,而不会触发Foo的析构函数。为了让RefCounted在delete this时能确定子类的类型,类Foo就得从RefCounted<Foo>继承,这样才能为在RefCounted中delete this提供便利:

delete static_cast<T*>(this);

在编译时T的类型会被确定为Foo,因此上面这句代码会触发Foo的析构函数,另外由于Foo继承于RefCounted,RefCounted的析构函数随后会调用(虽然啥也没干)。

--EOF--

红心地瓜 说:
2011年1月07日 21:47

写的简明易懂,谢谢

Lincoln 说:
2011年3月13日 02:26

但此时的RefCounted直接来一句delete this是不对的,因为如果有一个类Foo继承于RefCounted,那在RefCounted的成员函数里调用delete this只会触发RefCounted的析构函数,而不会触发Foo的析构函数。

对于上面这句话,有些疑问:如果把RefCounted的析构函数定义virtual的话,delete this是能够正常析构的;这里可能为了避免RefCounted使用虚函数表,故不把RefCounted的析构函数定义为virtual,转而使用模板的形式,从而使用了语句delete static_cast<T*>(this)。

tdns 说:
2011年5月12日 13:40

@Lincoln: 说的对,我也认为如此。
很好的一篇文章。一起学习webkit吧!

babysitting services 说:
2019年11月28日 13:46

In Whitespot cleanup, we have a very team involving competent professionals who will be well-trained along with certified to undertake the activity of cleanup office spots. Our special customers are very pleased with our cut-throat rates, and each of our commitment in order to meet them has become our main concern. If you do have a retail wall plug, work position or an workplace and call for cleaning solutions, you are generally assured to get premium along with quality service if you engage us to the cleaning of your respective offices, and also other commercial complexes.

maid agency dubai 说:
2021年1月29日 19:52

Cleaning service agencies Asia since the common option. Often, agencies through Asia would be the top range of other employers world wide. Aside in the lower costs, these companies work closely using the popular maids plus they know who're the experienced ones and also the maids really worth trusting. Usually these types of agencies originate from Hong Kong as well as Singapore as well as these nations operate globally underneath the strict rules of the government.

wall painting servic 说:
2021年7月01日 18:50

Many are appropriate as an important painter for one good measured contractor and painting business to put together experience. Quite a lot of who contain gone now on to be somewhat successful from this business have set off like it. Of course it will be up with the individual, but shortly, the most acquire sufficient self esteem to realize there is not any reason his particular employer should really be earning very good money although he can be just realizing that by the hour wage.

maid services dubai 说:
2021年8月26日 16:45

Clean-up makes yourself balanced in addition to clean your job spaces in addition to premises tidy. It is significant to maintain surroundings fresh and tidy and keep house fresh hygiene. Concerning hiring the most beneficial Cleaning Bureau in Dubai, guarantee that all what and stuff are wiped clean properly.

babysitting services 说:
2021年10月02日 16:54

As soon as you think about home housecleaning companies, this that all those things these vendors offer really are standard services that include dusting and additionally vacuuming. Marriage ceremony the lawsuit, though. For that matter, you may well hire a provider like this approach for various kinds of household needs. One for the types about duties that they may assist by means of is agency. If you can be a particularly unorganized people and do not know how to generate your family home organized, you’re able to hire a qualified for benefit. This isn't really something you need to be embarrassed to try. It could quite possibly actually change you, your mood and the majority other matters.

Grade 8 Result rajsh 说:
2022年8月28日 16:28

The Rajshahi Board is also completed the Junior School Certificate and Junior Dakil (Grade-8) terminal exams successfully under Secondary and Higher Secondary Education Board, and a huge number of students have appeared from all districts of Rajshahi Division, and those subject wise exams are completed between 1st to 3rd weeks at all schools across the country along with the divisional schools to the academic year of 2022. Both of JSC & JDC students are waiting to check their exam result with full marksheet in student wise to get total GPA grade for this year terminal exams, Grade 8 Result rajshahi Grade 8th standard is the most important examination for secondary education in the country and this is gateway to secondary education in the country, and the school education department will announce student wise result with total marksheet online and this year also published same like as previous years.

full time maids in d 说:
2023年9月04日 17:38

Do you really buy the best tools, food stuff, clothing or the rest? As a specialized painting building contractor, you recognise that buying less expensive tools can mean that you will possibly get yourself a tool multiple, once as soon as cheap system breaks and then the second time any time you buy an outstanding tool to change the less expensive tool who broke. Is cheap the right value? The litigant thinks on this when contemplating a residential home painting guess.

AC Board 7th Questi 说:
2023年9月14日 15:30

State Council of Educational Research and Training (SCERT) Jharkhand has Going to Conducted High School Aunval Exam 2024, SCERT Jharkhand which is Mainly Responsible for Conducting Exam Every year, This SCERT Jharkhand 7th Exam Very Year More Than 25 Laks of Students Attended, SCERT Jharkhand is Administered by the State Government of Jharkhand and Thrives to Improve the Quality of JAC Board 7th Question Paper 2024 Education in the state.SCERT Jharkhand is also Responsible for Prescribing the SCERT Jharkhand Model Paper 2024 for the Students Studying in the Jharkhand Affiliated Schools, Jharkhand Question Paper 2024 Designed by Senior Experts Study Materiel help the Students to get an idea about the Final Exam 2024.

pavzi.com 说:
2024年1月25日 23:48

Pavzi.com is a startup by passionate webmasters and bloggers who have a passion for providing engaging content that is accurate, interesting, and worthy to read. pavzi.com We are more like a web community where you can find different information, resources, and topics on day-to-day incidents or news. We provide you with the finest web content on every topic possible with the help of the editorial and content team.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter