开发者

Pure/const functions in C++

开发者 https://www.devze.com 2022-12-29 12:48 出处:网络
I\'m开发者_运维知识库 thinking of using pure/const functions more heavily in my C++ code. (pure/const attribute in GCC)

I'm开发者_运维知识库 thinking of using pure/const functions more heavily in my C++ code. (pure/const attribute in GCC)

However, I am curious how strict I should be about it and what could possibly break.

The most obvious case are debug outputs (in whatever form, could be on cout, in some file or in some custom debug class). I probably will have a lot of functions, which don't have any side effects despite this sort of debug output. No matter if the debug output is made or not, this will absolutely have no effect on the rest of my application.

Or another case I'm thinking of is the use of some SmartPointer class which may do some extra stuff in global memory when being in debug mode. If I use such an object in a pure/const function, it does have some slight side effects (in the sense that some memory probably will be different) which should not have any real side effects though (in the sense that the behaviour is in any way different).

Similar also for mutexes and other stuff. I can think of many complex cases where it has some side effects (in the sense of that some memory will be different, maybe even some threads are created, some filesystem manipulation is made, etc) but has no computational difference (all those side effects could very well be left out and I would even prefer that).

So, to summarize, I want to mark functions as pure/const which are not pure/const in a strict sense. An easy example:

int foo(int) __attribute__((const));

int bar(int x) {
   int sum = 0;
   for(int i = 0; i < 100; ++i)
       sum += foo(x);
   return sum;
}

int foo_callcounter = 0;

int main() {
   cout << "bar 42 = " << bar(42) << endl;
   cout << "foo callcounter = " << foo_callcounter << endl;
}

int foo(int x) {
   cout << "DEBUG: foo(" << x << ")" << endl;
   foo_callcounter++;
   return x; // or whatever
}

Note that the function foo is not const in a strict sense. Though, it doesn't matter what foo_callcounter is in the end. It also doesn't matter if the debug statement is not made (in case the function is not called).

I would expect the output:

DEBUG: foo(42)
bar 42 = 4200
foo callcounter = 1

And without optimisation:

DEBUG: foo(42) (100 times)
bar 42 = 4200
foo callcounter = 100

Both cases are totally fine because what only matters for my usecase is the return value of bar(42).

How does it work out in practice? If I mark such functions as pure/const, could it break anything (considering that the code is all correct)?


Note that I know that some compilers might not support this attribute at all. (BTW., I am collecting them here.) I also know how to make use of thes attributes in a way that the code stays portable (via #defines). Also, all compilers which are interesting to me support it in some way; so I don't care about if my code runs slower with compilers which do not.

I also know that the optimised code probably will look different depending on the compiler and even the compiler version.


Very relevant is also this LWN article "Implications of pure and constant functions", especially the "Cheats" chapter. (Thanks ArtemGr for the hint.)


I'm thinking of using pure/const functions more heavily in my C++ code.

That’s a slippery slope. These attributes are non-standard and their benefit is restricted mostly to micro-optimizations.

That’s not a good trade-off. Write clean code instead, don’t apply such micro-optimizations unless you’ve profiled carefully and there’s no way around it. Or not at all.

Notice that in principle these attributes are quite nice because they state implied assumptions of the functions explicitly for both the compiler and the programmer. That’s good. However, there are other methods of making similar assumptions explicit (including documentation). But since these attributes are non-standard, they have no place in normal code. They should be restricted to very judicious use in performance-critical libraries where the author tries to emit best code for every compiler. That is, the writer is aware of the fact that only GCC can use these attributes, and has made different choices for other compilers.


You could definitely break the portability of your code. And why would you want to implement your own smart pointer - learning experience apart? Aren't there enough of them available for you in (near) standard libraries?


I would expect the output:

I would expect the input:

int bar(int x) {
   return foo(x) * 100;
}

Your code actually looks strange for me. As a maintainer I would think that either foo actually has side effects or more likely rewrite it immediately to the above function.

How does it work out in practice? If I mark such functions as pure/const, could it break anything (considering that the code is all correct)?

If the code is all correct then no. But the chances that your code is correct are small. If your code is incorrect then this feature can mask out bugs:

int foo(int x) {
    globalmutex.lock();
    // complicated calculation code
        return -1;
    // more complicated calculation
    globalmutex.unlock();
    return x;
}

Now given the bar from above:

int main() {
    cout << bar(-1);
}

This terminates with __attribute__((const)) but deadlocks otherwise.

It also highly depends on the implementation. For example:

void f() {
    for(;;) 
    {
        globalmutex.unlock();
        cout << foo(42) << '\n';
        globalmutex.lock();
    }
}

Where the compiler should move the call foo(42)? Is it allowed to optimize this code? Not in general! So unless the loop is really trivial you have no benefits of your feature. But if your loop is trivial you can easily optimize it yourself.

EDIT: as Albert requested a less obvious situation, here it comes: F or example if you implement operator << for an ostream, you use the ostream::sentry which locks the stream buffer. Suppose you call pure/const f after you released or before you locked it. Someone uses this operator cout << YourType() and f also uses cout << "debug info". According to you the compiler is free to put the invocation of f into the critical section. Deadlock occurs.


I would examine the generated asm to see what difference they make. (My guess would be that switching from C++ streams to something else would yield more of a real benefit, see: http://typethinker.blogspot.com/2010/05/are-c-iostreams-really-slow.html )


I think nobody knows this (with the exception of gcc programmers), simply because you rely on undefined and undocumented behaviour, which can change from version to version. But how about something like this:


#ifdef NDEBUG \
    #define safe_pure __attribute__((pure)) \
#else \
    #define safe_pure \
#endif

I know it's not exactly what you want, but now you can use the pure attribute without breaking the rules.
If you do want to know the answer, you may ask in the gcc forums (mailing list, whatever), they should be able to give you the exact answer.
Meaning of the code: When NDEBUG (symbol used in assert macros) is defined, we don't debug, have no side effects, can use pure attribute. When it is defined, we have side effects, so it won't use pure attribute.

0

精彩评论

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

关注公众号