I have written a container class very similar to std::vector
.
It has a size()
member function, which I declared noexcept
, const
and constexpr
.
class my_vector {
...
constexpr auto size() const noexcept -> size_type {
assert(stride_ != 0);
return nelems_/stride_;
}
};
Since I switched to GCC 12, the compiler suggests me to add the __attribute__ ((pure))
.
error: function might be candidate for attribute 'pure' if it is known to return normally [-Werror=suggest-attribute=pure]
I would be happy to add the attribute but, first, is the function really pure
? I mean, this
is passed by reference and I think functions that take reference can't be "pure" because their arguments can be changed externally to the function (e.g. by another thread).
Is that the case?
Is it in generally safe to follow this recommendation by the compiler?
Finally, I don't understand the logic of this recommendations: if the compiler can determine the function is pure, then it should go ahead and do all the optimizations it can, instead of suggesting adding a non-standard language extension.
According to the gcc documentation
Even though hash takes a non-const pointer argument it must not modify the array it points to, or any other object whose value the rest of the program may depend on. However, the caller may safely change the contents of the array between successive calls to the function (doing so disables the optimization). The restriction also applies to member objects referenced by the this pointer in C++ non-static member functions
So it seems that member functions can be pure as long as they don't modify member variables. If they depend on member variables, the compiler will take care of recalling the method if those members change.