Re: static data in inline static member
On 19 Apr., 20:57, Helmut Jarausch <jarau...@igpm.rwth-aachen.de>
wrote:
Hi,
in the example below I have a static member function
which has static data.
--- file inline_static.h ---
#include <iostream>
class X {
int Count;
public:
X(int I) : Count(X_init(I)) {}
void print() { std::cout << "Count= " << Count << std::endl; }
static int X_init(int I) {
static int X_init_data;
if ( ! X_init_data ) X_init_data= I;
return X_init_data;
}
};
--- file inline_static.C ---
#include <iostream>
using std::cout; using std::cin; using std::cerr; using std::endl;
#include "Inline_static.h"
extern void Call_X(int);
int main() {
X X1(3);
Call_X(7);
X1.print();
return 0;
}
--- file Call_X.C ---
#include "Inline_static.h"
void Call_X(int I) {
X X2(I);
std::cout << "Here in Call_X\n";
X2.print();
std::cout << "leaving Call_X\n";
}
When running this (gcc-4.4.3), it outputs
Here in Call_X
Count= 3
leaving Call_X
Count= 3
which indicates there is only a single storage for the
static X_init_data;
Is this behaviour to be expected / guaranteed?
The behavior is guaranteed, see my reply to the recent
thread "Static local objects in inline functions".
A summary of the reply referring to the C++ 2003 is
that 9.3 [class.mfct]/6 says:
"A static local variable in a member function always refers
to the same object, whether or not the member function is
inline."
This is strengthened by an even more general statement
from 7.1.2/4:
"[..] A static local variable in an extern inline function
always refers to the same object. [..]"
in addition to the guarantee, that a static local object
is initialized exactly once as of 6.7/4:
"[..] Otherwise such an object is initialized the first
time control passes through its declaration; such an
object is considered initialized upon the completion of
its initialization. [..]"
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]