Static objects in function templates

D

Dave

#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::eek:fstream &Log()
{
static std::eek:fstream 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...
 
V

Victor Bazarov

Dave said:
#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::eek:fstream &Log()
{
static std::eek:fstream 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
 

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
474,202
Messages
2,571,057
Members
47,662
Latest member
sxarexu

Latest Threads

Top