throw(), pure and const flags on functions

Mark Mitchell mark@codesourcery.com
Tue Apr 14 15:12:00 GMT 2009


Paolo Carlini wrote:

>> Only functions both defined and used within single compilation unit are
>> fine without decorations.  LTO change definition of compilation unit to
>> "whole program without shared libraries".

Paolo, you asked my opinion on this.  My feeling is that, of course, it
would be best if the compiler could figure this out.  But, in many cases
it cannot even in theory (as soon as there's a function call to a
function it can't see, including a call through a function pointer).
Calls to C library functions are one special case; if those are not
decorated with "throw()", for example, then the compiler may not realize
that they do not throw.  That's not much of problem when using GLIBC,
since it has the annotations, but other C libraries are not as good
about that -- and GLIBC probably doesn't have "pure" and "const" in all
possible places.

My feeling is that it's appropriate for the library, as a foundation for
most C++ programs, to work hard to help the compiler.  If that means
adding the attributes in some places where it seems like it shouldn't be
necessary, at the expense of making the library a bit ugly, that's the
price of providing a truly excellent library.

The "throw()" markers in particular can be particularly valuable for
people concerned about code size; "pure" and "cost" are more about
performance.  For code size, there's no such thing as a "hot spot"; you
saving a byte here is just as good as a byte there.  But, of course,
there are hot spots for optimization; I'd only worry about "pure" and
"const" modifiers on functions we think are likely to be
performance-critical.

I realize that's something of a waffling answer.  That's because I think
it's a judgment call; you don't want to make a total mess of the
library, and you don't want to risk marking something "pure" or "const"
when it isn't -- as that will lead to wrong code! -- but you do want to
give the compiler the ability to optimize.

FWIW,

-- 
Mark Mitchell
CodeSourcery
mark@codesourcery.com
(650) 331-3385 x713



More information about the Libstdc++ mailing list