Legend

inline virtual function

标准C++编程:虚函数与内联

Josée Lajoie and Stanley Lippman

------------------------------------------------------------------------------
----

[This is the last installment of a column that was being published in C++ Repo
rt magazine. Since the magazine ceased publication before this installment cou
ld be published, Josée Lajoie and Stan Lippman were gracious enough to let us
publish it on the CUJ website. — mb]

 

曾经,我们常常在谈及C++时听到一个问题:“虚函数真的应该被申明为内联吗?”现在,
我们很少再听到这个问题了。反过来,我们现在听到的是“你不应该将print()函数内联。
将虚函数申明为内联是错误的。”

这么说有两个主要理由:(1)虚函数是在运行期判决的,而内联是编译期行为,所以不能从
这个(内联)申明上得到任何好处;(2)将虚函数申明为内联将造成此函数在可执行文件中
有多份拷贝,因此我们为一个无论如何都不能内联的函数付出了在空间上的处罚(WQ注,
所谓的内联函数非内联问题)。显然没脑子。

只是它并不真的正确。反思一下理由(1):在很多情况下,虚函数是静态判决的--尤其是
派生类的虚函数调用它的基类版本时。为什么会那么做?封装。一个很好的例子是析构函
数的静态调用链:基类的析构函数被派生类的析构函数触发。除了最初的一个外,所有的
析构函数的调用都是被静态判决的。不让基类的虚析构函数内联,就不能从中获益。这会
造成很大的差别吗?如果继承层次很深,而又有大量的对象需要析构,(答案是)“是的
”。

另外一个例子不涉及析构函数。想像我们正在设计一个图书馆出借管理程序。我们已经将
“位置”放入抽象类LibraryMaterial。当申明print()函数为纯虚函数时,我们也提供其
定义:打印出对象的位置。

class LibraryMaterial {

private:

MaterialLocation _loc; // shared data

// ...

 

public:

// declares pure virtual function

inline virtual void print( ostream& = cout ) = 0;

};

 

// we actually want to encapsulate the handling of the

// location of the material within a base class

// LibraryMaterial print() method - we just don’t want it

// invoked through the virtual interface. That is, it is

// only to be invoked within a derived class print() method

 

inline void

LibraryMaterial::

print( ostream &os ) { os << _loc; }

 

 

接着引入Book类;它的print()函数会输出书名、作者等等。在此之前,它先调用基类的L
ibraryMaterial::print()函数以显示位置信息。例如:

inline void

Book::

print( ostream &os )

{

// ok, this is resolved statically,

// and therefore is inline expanded ...

LibraryMaterial::print();

 

os << "title:" << _title

<< "author" << _author << endl;

}

AudioBook类从Book派生,引入了一个二选一的借出策略,并且加入了一些附加信息,比如
讲解员、格式等等。这些都将在它的print()函数中显示出来。在显示这些以前,它先调用
Book::print():

 

inline void

AudioBook::

print( ostream &os )

{

// ok, this is resolved statically,

// and therefore is inline expanded ...

Book::print();

os << "narrator:" << _narrator << endl;

}

在这个例子和析构函数的例子中,派生类的虚方法递增式地扩展其基类版本的功能,并以
调用链的方式被调用,只有最初一次调用是由虚体系决定的。这个没有被命名的继承树设
计模式,如果从不将虚函数申明为内联的话,显然会有些低效。

关于理由(2)的代码膨胀问题怎么说?好吧,思考一下。如果写出,

LibraryMaterial *p =

new AudioBook( "Mason & Dixon",

"Thomas Pynchon", "Johnny Depp" );

// ...

p->print();

此处的print()会内联吗?不,当然不会。这必须在运行期经过虚体系的判决。Okay。它会
导致此处的print()函数有它自己的定义体吗?也不会。调用被编译为类似于这种形式:


// Pseudo C++ Code

// Possible transformation of p->print()

( *p->_vptr[ 2 ] )( p );

那个2是print()函数在相应的虚函数表中的位置。因为这个对print()的调用是通过函数指
针_vptr[2]进行的,编译器不能静态决定被调用函数的位置,并且函数不能被内联。

当然,内联的虚函数print()的定义必须出现在可执行文件中的某处,代码才能正确执行。
也就是说,至少需要一个定义体,以便将它的地址放入虚函数表。编译器如何决定何时产
生那一个定义体的呢?一个实现策略是在产生那类的虚函数表时同时产生那个定义体。这
意味着针对为一个类所生成的每个虚函数表实例,每个内联的虚函数的一个实例也被产生

在可执行文件中,为一个类产生的虚函数表,实际上有多少个?啊,很好,问得好。C++标
准规定了虚函数在行为上的要求;但它没有规定实现虚函数上的要求。既然虚函数表的存
在不是C++标准所要求的,明显标准也没有进一步要求如何处理虚函数表以及生成多少次。
最佳的数目当然是“一次”。例如,Stroustrup的原始cfront实现版本,在大部份情况下
聪明地达成了这一点。 (Stan和Andy Koenig描述了其算法,发表于1990年3月,C++ Repo
rt,“Optimizing Virtual Tables in C++ Release 2.0.”)

此外,C++标准现在要求内联函数的行为要满足好象程序中只存在一个定义体,即使这个函
数可能被定义在不同的文件中。新的规则是说满足规定的实现版本,行为上应该好象只生
成了一个实例。一旦标准的这一点被广泛采用,对内联函数潜在的代码膨胀问题的关注应
该消失了。

C++社群中存在着一个冲突:教学上需要规则表现为简单的检查表vs实践中需要明智地依据
环境而运用规则。前者是对语言的复杂度的回应;后者,是对我们构造的解决方案的复杂
度的回应。何时将虚函数申明为内联的问题,是这种冲突的一个很好的例证。

 

About the Authors
Stanley Lippman was the software Technical Director for the Firebird segment o
f Disney's Fantasia 2000. He was recently technical lead on the ToonShooter im
age capture and playback system under Linux for DreamWorks Feature Animation a
nd consulted with the Jet Propulsion Laboratory. He is currently IT Training P
rogram Chair for You-niversity.com, an e-learning training company. He can be
reached at stanleyl@you-niversity, www.you-niversity.com, and www.objectwrite.
com.

Josée Lajoie is currently doing her Master's degree in Computer Graphics at t
he University Waterloo. Previously, she was a member of the C/C++ compiler dev
elopment team at the IBM Canada Laboratory and was the chair of the core langu
age working group for the ANSI/ISO C++ Standard Committee. She can be reached
at jlajoie@cgl.uwaterloo.ca.

posted on 2007-04-26 14:55 Legend 阅读(780) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理