开发者

Why doesn't GCC force parameters in __attribute__((pure)) functions to be const?

The following code compiles without warnings under GCC 4.2, and as far as I can tell, it really shouldn't:

#include <fstream>

__attribute开发者_JS百科__((pure))
double UnpureFunction(double* x) {
  x[0] = 42;
  return 43;
}

int main () {
  double x[] = {0};
  double y = UnpureFunction(x);
  printf("%.2f %.2f\n", x[0], y);
}

(It prints "42.00 43.00".)

As I understand it, the pure attribute tells the compiler that the function has no external effects (see the section on "pure" here). But UnpureFunction is modifying its parameter. Why is this allowed to happen? At the very minimum, the compiler could automatically make every parameter const.


As far as I know, pure is your promise to the compiler, but it won't try and verify that you're not lying. Even if it did force parameters to be const, those parameters could be lying (e.g. an object might have a mutable member that's modified when your code calls a member function).

If you're looking for const correctness, use const parameters. The pure and const attributes are there to provide hints that can be used for optimization.


First, if the function is forwarding the const/non-const of its parameters, then the function could still be pure, and some later function will modify it. That is the non-const reference doesn't dictate that the function specifically will modify it, but rather a non-const reference grants the access that some operation, down the chain, will modify the state(ie produce side effects). For example, if I want to write a function that returns the first element of a vector of ints:

int& first(std::vector<int>& v) __attribute__((pure))
{
    return *(v.begin());
}

I can declare it as pure even though it may take a non-const reference, because first() doesn't modify the vector. Instead it only retrieves the first element(generally that doesn't produce side effects). Some operation later on could modify the value. In this sense it is only forwarding the const/non-const of the range.

Secondly, even though the parameters are const, it still doesn't guarantee that there are no side effect, since a class can declare fields as modifiable even when the class is const, using the keyword mutable.


Ah, dumb question. The __attribute__((pure)) construct allows the programmer to use pointers as output variables, as is standard. I guess this means I can't avoid lots of boilerplate consts in front of my variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜