On 1 sep, 21:39, Greg Herlihy <gre...@mac.com> wrote:
To avoid the overhead of initializing a "T" object each time
call_f<T>() is invoked, simply have the T object declared inside
call_f() - be static as well:
template <class T>
void call_f(int x)
{
static T t;
t.f(x);
}
The problem is that the compiler does not optimize
the singleton<T>::get() call away when T::f is static because
obtaining the singleton reference has side effects, namely the
creation of t the first time get() is called. The translation
of your proposal to this scenario:
template <class T>
void call_f(int x)
{
T& t=singleton<T>::get();
t.f(x);
}
is also suboptimal because the *presence* of a static local incurs
an execution overhead every time call_f is invoked, precisely
for the same reason as above, first-time-creation code must be
executed on every call_f invocation.
[ comp.lang.c++.moderated. First time posters: Do this! ]