pure/const functions in C++0x
In C++98/C++03, there are no pure/const function keywords in the language.
Has this changed in C++0x?
If so, is it possible to set such a flag even on function objects (
std::function
)? So I can pass some function pointer or lambda functions and additional give the information that it is a开发者_高级运维 pure/const function? The called function may have an optimized execution path for such a function.Is there some way to check if a given function is pure/const? I.e. for example, if there is such flag on
std::function
as described above, I probably could just check that flag. But maybe there is even a more general way.
If it has not changed, why not? I think it might be quite useful to have such a support.
Are there any open proposals about it?
- Has this changed in C++0x?
No. There is a constexpr
but it means compile time constant. If its parameters are constexprs
too then it's executed at compile time, but it's a regular function otherwise. Since they must be defined in the same translation unit and consist of a single return statement they probably will be inlined and the above optimization will be performed. It can't be used to provide the compiler information about externally linked function.
If it has not changed, why not? I think it might be quite useful to have such a support.
Actually I don't think you need it. The language is already too big, and the programmer can easily rewrite this code to be more efficient based on her knowledge anyway. Unlike restrict
it doesn't provide any info that can't be expressed by other means.
Are there any open proposals about it?
I haven't seen any committee papers on that topic.
gcc uses __attribute__(( <attr> ))
to define extra attributes on functions.
pure: only accesses (but does not modify) parameters and global memory. GCC uses this information to determine if the optimizer can completely omit repeated calls to the function (local-memoization). Two notable pure functions are
strlen
andmemcmp
.const: not to be confused with C++ const, const functions only accesses parameters and those parameters must not be pointers. It is basically a more restricted version of
pure
. The optimizer treatsconst
functions that same aspure
. Though in theory it could perform more aggressive (non-local) memoization than it does forpure
.
C++11's new attribute syntax (§7.6) was designed to do just this sort of thing. Currently you cannot use C++'s attribute syntax to set GCC attributes, but that will change in future gcc versions.
So you will be able to assign the pure
attribute to functions using the attribute syntax. But there isn't a standard pure
attribute. pure will be compiler specific, but it will do the right thing on gcc.
For the curious, here is the list of the standard attributes:
- align
- noreturn
overridehidingbase_check- carries_dependency
精彩评论