1

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.

alfC
  • 14,261
  • 4
  • 67
  • 118
  • 1
    `if the compiler can determine the function is pure, then it should go ahead` ? _You requested_ the warning, so you are getting it. If you don't want it, don't request it. – KamilCuk Aug 17 '22 at 06:24
  • @KamilCuk, good point. I activate all the warnings I can to learn about opportunities to improve the code. I wonder if this warning actually can improve the code in this case in particular. – alfC Aug 17 '22 at 06:31
  • 1
    "pure" means that given the same arguments the function will return the same result. For member function this includes the hidden `this` argument. The compiler will detect when `this` changes. PS: use modern c++ and `[[pure]]` of `[[gcc::pure]]`, can't remember if that is an extension. – Goswin von Brederlow Aug 17 '22 at 06:53

1 Answers1

2

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.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60