home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!taumet!mike
- From: mike@taumet.com (Mike Ball)
- Subject: Re: inline virtual functions
- Message-ID: <1992Sep15.152147.12121@taumet.com>
- Organization: TauMetric Corporation, San Diego
- References: <1992Sep15.023336.1403@cs.brown.edu>
- Date: Tue, 15 Sep 1992 15:21:47 GMT
- Lines: 61
-
- In article <1992Sep15.023336.1403@cs.brown.edu> sdm@cs.brown.edu (Scott Meyers) writes:
- >For all the compilers with which I am familiar, inline virtual functions
- >are oxymoronic: the function bodies are never inlined, and the object file
- >for each translation unit seeing the definition of the function receives a
- >static copy of the function. I tested this using cfront 3.0 and g++ 2.2.2,
- >and both behaved as I have described, neither issuing a warning about not
- >inlining a function.
-
- In the case of both cfront and our own compiler inline virtual functions
- will be generated inline when the compiler can determine the exact function
- to execute. This can be quite hard to determine for a virtual function, but
- you can test this on your own compiler by writing A::f() instead of f().
- Different compilers go to different amounts of trouble to make this
- optimization.
-
- In the example below,
-
- struct s {
- virtual int f();
- inline virtual int g() {return 1;}
- s(){}
- };
-
- extern s* sp;
- extern int i, j;
-
- void foo() {
- s sv;
- i = sv.g();
- j = sp->g();
- }
-
- Our own compiler generates a non-virtual call to initialize i and a virtual
- call to initialize j. I was surprised to discover that cfront 3.0 generates
- virtual calls in both cases.
-
- >Many people have discovered this behavior in current compilers, and so the
- >following rule is widely followed: "never define an inline virtual
- >function." This is a pity, because it's the kind of rule that is easy to
- >remember, hence people will continue to follow it even when C++ compilers
- >become agressive enough in their optimization to be able to generate
- >inlined calls to virtual functions.
-
- Inlined polymorphic calls to virtual functions are unlikely unless the
- compiler is applying specialization techniques or has global knowledge of
- the program. In fact, though, declaring them inline does no harm unless tools
- like the debugger can't handle inline functions.
-
- >I was involved in a discussion of this issue today when it was suggested
- >that compilers should generate only a single copy of an out-of-line virtual
- >function, and that the single translation unit in which the function
- >definition should be generated should be the same as the one containing the
- >class's vtbl. This seems sensible to me, so I was wondering: is there some
- >reason why compiler implementers don't do this?
-
- No. In general, that's what will happen. Both cfront and our own compiler
- do exactly that in the case above.
-
- --
- Michael S. Ball (mike@taumet.com)
- TauMetric Corporation
-