When variables are declared in scope {}, will they still use memory after?

in this example, although I will never use the WNDCLASSEX, x, y, cx, cy variables, they will still use memory when I'm in a message loop:

int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpArgs, int iCmdShow) { WNDCLASSEX wc; ... RegisterClassEx(&wc); const int cx = 640; const int cy = 480; // center of the screen int x = (GetSystemMetrics(SM_CXSCREEN) - cx) / 2; int y = (GetSystemMetrics(SM_CXSCREEN) - cy) / 2; CreateWindow(..., x, y, cx, cy, ...); MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; } 

But I wonder if I put them in scope, will they use memory during the message loop? eg.

 int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpArgs, int iCmdShow) { { WNDCLASSEX wc; ... RegisterClassEx(&wc); const int cx = 640; const int cy = 480; // center of the screen int x = (GetSystemMetrics(SM_CXSCREEN) - cx) / 2; int y = (GetSystemMetrics(SM_CXSCREEN) - cy) / 2; CreateWindow(..., x, y, cx, cy, ...); } MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; } 

or maybe if I put them in two functions and named them in winmain, for example.

 wnd_register(hInst); wnd_create(hInst); 

won't let them use memory?

+8
c ++ variables scope
source share
9 answers

The compiler has many possibilities for handling simple local users, as in your examples. They can live on the stack, they can only exist as immediate values ​​in machine codes, or they can just live in registers. Stack space is usually allocated when entering a function. The compiler subtracts some value from the stack pointer to free up space for all local users. When the function returns, the stack pointer returns to its original value. This is usually not done when exiting from different blocks. Most compilers will attempt to aggressively reuse stack space as soon as the variables are no longer used. In your example, it would be perfectly legal for x and msg to have an exact address on the stack, since their use is not overlapping.

My answer to this question describes in more detail how local variables are allocated on the stack.

In your examples, the constants cx and cy will most likely not have a memory backup at runtime and will simply be the immediate values ​​in the generated code. x and y will most likely be written to the registers until they need to be pushed onto the stack to call CreateWindow. wc and msg will almost certainly be on the stack.

You should not worry about micro-optimization at this level - let the compiler allocate space for local variables as you like. By default, you have 1 MB of stack, the amount of data consumed by these variables is not even recorded as noise. Spend time worrying about more interesting issues.

+6
source share

Maybe not, but this is an implementation detail. They will be destroyed, though (calls to destructors will be made, if any). Regardless of when the system recovers the memory used for automatic storage, the standard is not specified. Most of them return afaik almost immediately.

+3
source share

Well, I'm not sure if they use memory or what the standard says about it.

I know that at the end of the memory block {}, the destructor will be called, and the variables will be inaccessible. This may mean that although it is not released, at least it can be reused.

Example:

 struct Foo { Foo(void) { std::cout << "Hi!"; } ~Foo(void) { std::cout << "Bye!"; } }; int main(int argc, char * argv[]) { { Foo bar; // <- Prints Hi! } // <- Prints Bye! // Memory used by bar is now available. } 

Edit: Thanks Tomalak Geret'kal;)

+1
source share

One magic tip: Trust your compiler. It optimizes. This is smart. It is optimized better than most of us can.

If you are not sure, use the profiler or view the output from the compiler assembly after optimization. But remember - trivial optimizations are something that you should not do in your code, as this is pointless and only harms your readability of the code.

Some variables (especially constants) will not use any memory on the stack, because they will either be mapped to CPU registers or built directly into assembler instructions.

This means that the codes are:

 func(123+456*198*value); 

and

 int a = 123; int b = 56; int c = 400; int d = b+c; int e = d*198; e *= value; e += a; func(e); 

will compile in exactly the same way (if the variables are never used again).

Seriously, don’t worry. If you want to optimize, optimize from an algorithmic point of view, not a syntactic one.
+1
source share

Oh my god no, four integers in memory while the program is running, what a loss!

  • Try, just a simple mailbox trying to print them should be enough (I think).
  • Do not even mind.
0
source share

Your declared variables inside {} will go out of scope and be lost. In fact, you will get a compilation error if you try to use them outside the block: "x" is not declared. However, this is careless. Just make a function for this code, as you said in your edit. Keeping your main () as few lines as possible is a simple programming practice.

0
source share

They will not. They will live only until the end of their enclosing block.

0
source share

If you put them in a nested area inside a function (your first option), then when the control reaches the end of the area, the variables become inaccessible (either a compilation error if you use them directly, or the runtime is undefined if you keep a pointer to one of them ), their destructors are started (if there are destructors), and the implementation can reuse their storage space in the stack frame. But standards do not require reuse of space.

If you divide your function into two parts (your second option) ... in terms of the standard hair layout, there is no difference! When the function returns, the variables become inaccessible, their destructors are started, and the implementation can reuse their storage space, but this is not necessary. And there were serious implementations - albeit not C / C ++ - that did not immediately process this memory: see the most famous article, β€œ Cheney on the MTA ”

However, all the C / C ++ implementations that I now know about overwrite the memory allocated for the local function when the function returns. Multiplying memory by variables of nested local regions is much less obvious. In any case, as mentioned by several other people, in this context you should not worry about a few tens of bytes of stack space.

Personally, I would break your code into two functions only because each method performs only one task. This is usually best for long term maintenance.

0
source share

In the general case, yes, if the variable is always on the stack, then the space for it will be taken on the stack for the entire duration of the inclusion function. Compilers usually calculate the maximum amount of space that function variables can occupy, and then make the function allocate all of this right away when the function is first introduced. However, constructors and destructors will still cause entry and exit from internal areas. The space for variables in one area can be reused to represent variables from a separate area.

0
source share

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


All Articles