The GCC C++ compiler offers a family of extensions via function attributes, such as:
int square(int) __attribute__((const));
Two attributes in particular, const
and pure
, allow you to declare that a function's evaluation has no side effects and depends only on its arguments (const
), or only on its arguments and global variables (pure
). This allows for common subexpression elimination, which may have the effect that such a function gets called fewer times than it is written in the code.
My question is whether this can be used safely, correctly and sensibly for virtual member functions:
struct Foo
{
virtual int square(int) __attribute__((pure)); // does that make sense?
};
Does this have any sensible semantics? Is it allowed at all? Or is it just ignored? I'm afraid I can't find the answer to this in the GCC documentation.
The reason for this question is that there is a family of compiler options -Wsuggest-attribute
which make GCC produce suggestions of where those attributes might be placed to improve the code. However, it seems to end up making these suggestions even for virtual functions, and I wonder whether those suggestions should be taken seriously.
const
andpure
:( – Yasukoyataghan__attribute__((const))
was added a very long time ago, a time when "const
" had just been invented, so it didn't have a generally understood meaning, and I guess someone thought equating it with the programming-language-theoretic "pure" made sense. The weaker__attribute__((pure))
was added much later, and at that point there was too much installed base of__attribute__((const))
to swap them. – Deporteeconst
, why not. My main issue is withpure
. A different name would have been great, since the generally understood concept of purity is that repeatedly invoking the same function with the same parameters should produce the same results, which is broken here by the dependency on global variables. – Yasukoyataghanconst
. – Deportee