Static const only created once?

1
2
3
void xz() {
	static const vector <string> find = {"val", "val2"};
}


I dont want to create the variable "find" all over again every time I call this function.

Is the variable only created once if I do it like above?
Last edited on
https://en.cppreference.com/w/cpp/language/storage_duration

static storage duration. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists.

Your variable and it's value persists between function calls.
Thanks Furry!

Can I interpret it as if the static definition/declaration gets ignored when the function runs?
The static storage classifier is not ignored when the function is called no matter how many times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

void func();

int main()
{
   for (int i { }; i < 10; i++)
   {
      func();
   }
}

void func()
{
   // created every time the function is called
   int var1 { }; // <--- initialized to zero via uniform initialization

   // created ONCE, when the function is called the first time
   // each subsequent call the value is retained from the previous call
   static int var2 { };

   std::cout << var1 << ' ' << var2 << '\n';

   // change the variables' values
   var1++; var2++;
}
const, of course, means your vector's value(s) are unmodifiable. You can't add or delete any elements. Neither can you modify the elements.
I understand that as once time defintion. I have already used something similar and just ran one time.
be careful with it if you start using threads.
It is completely safe even in the presence of multiple threads.
The initialisation does not recursively reenter the block.
It is an object of a const-qualified type; so immutable after it is initialised.
*slaps forehead*

Immutable...that's what I meant when I said unmodifiable.
Since they are const, do they need to be strings? You could save the program time and space by using the C strings directly:
static const char *find[] = {"val1", "val2"};
The overhead of using std::string would be quite irrelevant here; these are constructed just once in the program.

If space is actually a concern use std::string_view; that would not compromise code quality / introduce extra programmer overhead. static const std::array< std::string_view, 2 > find { { "val", "val2" } };
Topic archived. No new replies allowed.