What is the pratical utility of declaring a static variable in function? I understood the lifetime of a static variable declared within a function, but I can not figure a practical example where it might be useful (or necessary) to declare a static variable in a function. Could you give me an example of a problem that should be solved in this way?
By declaring a static variable in a function, you
limit the variable's scope, and
delay dynamic initialization to the first time execution passes through the declaration.
In some cases the limited scope is most important, e.g. for a local constant.
In other cases the delayed dynamic initialization is the most important, e.g. for a Meyers' singleton.
One practical use case is to define a constant of arbitrary type with effectively external linkage (so that it won't be duplicated in each translation unit), in a header file, like
inline
auto get_t()
-> T const&
{
static T const the_t;
return the_t;
}
T const& t = get_t();
Here the reference takes up minimum space.
This can however also be done via the "templated constant" trick, or in C++11 via constexpr
, if applicable.
For comparison, here's the same as the above expressed with the "templated constant" trick (again, the purpose is to provide the extern linkage constant in a header file):
template< class Dummy >
struct The_t_constant
{
static T const value;
};
template< class Dummy >
T const The_t_constant<Dummy>::value;
T const& t = The_t_constant<void>::value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With