When does initialization of static member variables occur?

J

Joseph Turian

When does initialization of static member variables occur?

In the following code fragment, is m_start_time automatically
initialized right before main()?
[This is the desired effect.]

Or is m_start_time uninitialized until the first time I use a static
method in stats?

Thanks

Joseph

==

stats.H:
class stats {
...
static time_t m_start_time;
};

==

stats.C:
time_t get_start_time() {
time_t t;
time(&t);
return t;
}

time_t stats::m_start_time = get_start_time();

==
 
V

Victor Bazarov

Joseph said:
When does initialization of static member variables occur?

At some point before 'main' is called, if they are defined.
In the following code fragment, is m_start_time automatically
initialized right before main()?
Yes.

[This is the desired effect.]

Or is m_start_time uninitialized until the first time I use a static
method in stats?
No.


Thanks

Joseph

==

stats.H:
class stats {
...
static time_t m_start_time;
};

==

stats.C:
time_t get_start_time() {
time_t t;
time(&t);
return t;

Why couldn't you just write

return time(0);

instead of the three lines?
}

time_t stats::m_start_time = get_start_time();

==

V
 
G

Greg

Victor said:
At some point before 'main' is called, if they are defined.


Yes.

Not necessarily. It is certain that m_start_time will be
zero-iniitalized before main() executes. But since m_start_time is not
initialized with a constant expression, its initialization is dynamic,
not static. §3.6.2/1. Therefore, it is implementation-defined whether
m_start_time will be initialized before main() is called. In other
words, your compiler documentation will have the answer to this
question.
[This is the desired effect.]

Or is m_start_time uninitialized until the first time I use a static
method in stats?

No.

Possibly. It is certain that m_start_time will be completely
initialized before the first use of any object or function in its
translation unit (i.e. source file) §3.6.2/3. Of course such use could
occur well after the program has started.

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top