Reputation: 1159
The static
keyword, as far as I know, does two things:
So, it is used if:
But, what if the variable is so large, but doesn't need to be available all the time, and keeping it all the time in the heap would be memory expensive ?
What shall I do if I face that situation ? I'm not sure I totally understand the purpose of the static keyword.
Upvotes: 0
Views: 720
Reputation: 2540
The static
keyword in c++ is more or less related to persistent storage as you describe it, but with several nuances according to the specific context:
--static variable in global scope.
--static variable in local function scope.
--static class member.
--static class method.
I suggest you look up at all of these cases in some tutorial.
A conceptual point that I believe you are misunderstanding is that static
per se has nothing to do with size related storage efficiency. If you need to handle large data, you do this using dynamic allocation/deallocation (new
/delete
). In other words, this is a memory management issue, and the various techniques to deal with this have to do with constructors, destructors, smart pointers, etc...
Upvotes: 1
Reputation: 30136
The keyword static
can probably be seen as somewhat "overloaded".
The following usage-options are all viable:
In terms of runtime, all types of static variables are essentially the same. They all reside in the data-section of the program, and their addresses remain constant throughout the execution of the program. So the only difference between them is during compilation, in the scope of declaration:
In terms of runtime, all types of functions (static and non-static) are essentially the same. They all reside in the code-section of the program, and their addresses remain constant throughout the execution of the program. So the only difference between them is during compilation, in the scope of declaration:
Upvotes: 0