Amr Ayman
Amr Ayman

Reputation: 1159

Static storage and large objects

The static keyword, as far as I know, does two things:

  1. It allocates the variable on the heap rather than the stack. Storage
  2. It marks the lifetime of the variable as long as the lifetime of its parent process. Scope

So, it is used if:

  1. The variable is so large that it would overflow the stack. Storage use
  2. The variable needs to be available for the lifetime of the process for the function. Scope use

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

Answers (2)

Emerald Weapon
Emerald Weapon

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

barak manos
barak manos

Reputation: 30136

The keyword static can probably be seen as somewhat "overloaded".

The following usage-options are all viable:

  • Static local variables
  • Static global variables
  • Static member variables
  • Static global functions
  • Static member functions

Variables:

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:

  • Static local variable: recognized by the compiler only in the scope of the function
  • Static global variable: recognized by the compiler only in the scope of the file
  • Static member variable: recognized by the compiler only in the scope of the class

Functions:

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:

  • Static global function: recognized by the compiler only in the scope of the file
  • Static member function: recognized by the compiler only in the scope of the class

Upvotes: 0

Related Questions