Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are modern C++ compilers able to avoid calling a const function twice under some conditions?

For instance, if I have this code:

class SomeDataProcessor { public:     bool calc(const SomeData & d1, const SomeData & d2) const; private:     //Some non-mutable, non-static member variables }  SomeDataProcessor sdp; SomeData data1; SomeData data2;  someObscureFunction(sdp.calc(data1, data2),                     sdp.calc(data1, data2)); 

Let's consider the potentially equivalent code:

bool b = sdp.calc(data1, data2); someObscureFunction(b,b); 

For this to be valid, the calc() function should meet some requirements, and for the example I call the property _pure_const_formula_

A _pure_const_formula_ would:

  • Not change any member, static or global variable state
  • Call only _pure_const_formula_ functions
  • Maybe some other conditions that I don't have in mind

For instance, calling a random number generator would not fit these requirements.

Is the compiler allowed to replace the first code with the second one, even if it needs to dig recursively into called functions? Are modern compilers able to do this?

like image 988
galinette Avatar asked Feb 14 '17 13:02

galinette


People also ask

What does a compiler do with const?

When you declare a const in your program, int const x = 2; Compiler can optimize away this const by not providing storage for this variable; instead it can be added to the symbol table. So a subsequent read just needs indirection into the symbol table rather than instructions to fetch value from memory.

Is const faster in C?

No, const does not help the compiler make faster code.

Why would you use const sometimes?

The const keyword allows you to specify a semantic constraint: an object should not be modified. And compilers will enforce that constraint. This will allow you to communicate to the compiler and to other developers that the object should remain invariant.

Why it is good practice to declare as many methods as const as you can?

It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.


1 Answers

GCC has the pure attribute (used as __attribute__((pure))) for functions which tells the compiler that redundant calls can be eliminated. It's used e.g. on strlen.

I'm not aware of any compiler doing this automatically, especially considering the fact that the functions to be called may not be available in source form, and the object file formats contain no metadata about whether a function is pure or not.

like image 154
Tamás Zahola Avatar answered Sep 24 '22 08:09

Tamás Zahola