What is the usefulness of declaring a static variable in a function?

What is the practical usefulness of declaring a static variable in a function? I understood the lifetime of a static variable declared inside a function, but I cannot imagine a practical example where it would 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?

+4
source share
7 answers

Imagine that a function needs some value, which is very expensive to calculate, does not change, and may not be needed at all. Therefore, you want to calculate it once, when it is needed first, but not earlier.

+3
source

By declaring a static variable in a function, you

  • limit the scope of the variable and

  • The dynamic initialization delay is first performed through the declaration.

In some cases, limited volume is most important, for example. for a local constant.

In other cases, delayed dynamic initialization is most important, for example. for singleton Meyers.


( ) ,

inline
auto get_t()
    -> T const&
{
    static T const the_t;
    return the_t;
}

T const& t = get_t();

.

++ 11 constexpr, .

, , , ( , ):

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;
+6

, , ++ static . , , const , .

:

static const int indices[] = {1, 3, 5, 7, ...};
for (int index : indices) {
   // do something
}

static const char sqlCommand[] = "INSERT INTO ... some long statement ...";
if (!m_database.prepare(sqlCommand, ...)) {
   m_log.error("Error preparing query: %s", sqlCommand);
   // ...
}

, , [1].

, ( , ), .., , , - .

[1] , .

+2

( ).

class Foo
{
    // ...
    static Foo* instance();
}

Foo* Foo::instance() {
    static Foo *obj = nullptr;
    if (obj == nullptr) {
        obj = new Foo();
        // ...
    }
    return obj;
}
+1

.

1

, , . "" , "". .

std::string const&  getLongName(std::string const& shortName)
{
   static std::map<std::string, std::string> unitsmap;
   static std::string unknownUnit("Unknown Unit");
   if ( unitsmap.empty() )
   {
       unitsmap["m"] = "meter";
       unitsmap["cm"] = "centimeter";
       unitsmap["mm"] = "millimeter";
       unitsmap["g"] = "gram";
       unitsmap["kg"] = "kilogram";

       // etc.
   }
   std::map<std::string, std::stirng>::iterator f = unitsmap.find(shortName);
   if ( f != unitsmap.end() )
   {
      return f->second;
   }
   else
   {
      return unknownUnit;
   }
}

2

Singleton Pattern .

class Singleton
{
   public:
      static Singleton* instance()
      {
        static Singleton* theInstance = NULL;
        if ( theInstance == NULL )
        {
           theInstance = new Singleton;
        }
        return theInstance;
     }

  private:
     Singleton() {}
};
+1

, . , .

int DoSomething()
{
   static foo * myFoo = new foo();//foos constructor may read from the environment or whatever else 
                                  //I only need it the first time I call DoSomething if I never call DoSomthing its never created


}
0

, , :

void foo()
{
static int count;
// ...
count++;
// ...
}

Since it is declared static, it is initialized to zero only once, when the program loads. It is different from

static int count = 0;

and in this case it will be set to zero each time the function is called.

0
source

Source: https://habr.com/ru/post/1536868/


All Articles