> Or does the compiler see this and ignore the static keyword to reduce the amount of memory allocated to store static objects?
The compiler can optimize away any object altogether, as long as the observable behaviour of the program does not change. In the example, both that static int objects will be optimised away as if the program was
1 2
|
void Function( ) {}
int main() {}
| |
... conforming implementations are required to emulate (only) the observable behavior of the abstract machine ... - IS
The code that is generated for:
1 2 3 4 5 6 7 8 9 10
|
int function( char c )
{
int a = c + 5 ;
++a ; // a == c+6
++a ; // a == c+7
int b = a - c ; // b == 7
if( b < 2 ) // b < 2 == false
std::cout << "b is less than 2\n" ; // dead code
return b - 5 ; // b - 5 == 7 - 5 == 2 => return 2 ;
}
| |
is:
1 2 3
|
__Z8functionc:
movl $2, %eax
ret
| |
However, if the initialization or de-initialisation of an unused static variable has "side effects" - some effect that is observable, it can not be optimized away. For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
struct A
{
char cstr[100] ;
#ifdef HAS_SIDE_EFFECTS
A() { std::cout << "A::constructor\n" ; }
~A() { std::cout << "A::destructor\n" ; }
#endif // HAS_SIDE_EFFECTS
};
void foobar( int a )
{
if( a > 1 )
{
static A static_object ;
}
}
int main( int argc, char* argv[] )
{
foobar( argc ) ;
}
| |
The code generated for foobar is just a single
ret
instruction if
HAS_SIDE_EFFECTS
is not defined. Compile with
-D HAS_SIDE_EFFECTS
and the static object can't be optimized away.
Note: There are a few places where the IS allows optimisations "even if there are side effects" - for example in copy-elision.