Re: Detecting memfun staticness
On 1 sep, 21:39, Greg Herlihy <gre...@mac.com> wrote:
On Aug 28, 1:34 pm, Joaqu?n M L?pez Mu?oz <joaq...@tid.es> wrote:
Say I've got the following template function
template<typename T>
void call_f(int x)
{
T t;
t.f(x);
}
[...]
And now I'd like to optimize call_f's implementation by avoiding the
creation of the T object when it is not necessary (as in bar, whose
memfun f is static).
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);
}
Well, my probem statement is a simplification of the real scenario;
actually, I'm not creating t, but rather retrieving a reference to
it through a Meyers singleton, something like this:
template<class T>
struct singleton
{
static T& get()
{
static T t;
return t;
}
};
template <class T>
void call_f(int x)
{
singleton<T>::get().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.
Joaqu?n M L?pez Mu?oz
Telef?nica, Investigaci?n y Desarrollo
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]