By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,192 Members | 802 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,192 IT Pros & Developers. It's quick & easy.

Static objects in function templates

P: n/a
#ifndef INCLUDED
#define INCLUDED

#include <fstream>

// Instantiate the template below with these constants.
const unsigned int LOG_1 = 0;
const unsigned int LOG_2 = 1;
// ...

template <unsigned int>
std::ofstream &Log()
{
static std::ofstream Strm;

return Strm;
}

#endif

Am I guaranteed that every translation unit that calls, for example,
Log<LOG_1>(), will get a reference to the exact same stream object?

I seem to recall that there are some unusual cases where a static object can
end up being created more than once...
Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Dave wrote:
#ifndef INCLUDED
#define INCLUDED

#include <fstream>

// Instantiate the template below with these constants.
const unsigned int LOG_1 = 0;
const unsigned int LOG_2 = 1;
// ...

template <unsigned int>
std::ofstream &Log()
{
static std::ofstream Strm;

return Strm;
}

#endif

Am I guaranteed that every translation unit that calls, for example,
Log<LOG_1>(), will get a reference to the exact same stream object?

I seem to recall that there are some unusual cases where a static object can
end up being created more than once...


The whole idea is that there is only one instance of 'Log' function
specialised on a particular value of the template argument. So, yes,
the language says that any occurrence of calling that function should
go to the same instance and give the same reference back.

You could of course verify it by comparing the addresses of the objects
you get back from the function...

V
Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.