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.