-2

I know that C++ holds memory management internally with a lot of given points, and I know of the delete command to remove dynamically allocated data, and this question, could seem pointless within the fact that it may not ever come to be an issue due to the destruction of variables outside of the scope of the function that is using them, but is it possible to use a function such like delete to remove a variable that the user is no longer putting to use. Like say that you are on a heavily memory depleted piece of hardware, and need to make sure that even something as small as the 4 bytes that an integer normally takes up are given straight back. Is it possible to do this without wrapping the variable inside some function to make the assembler know to remove it immediately? This is in a sense of a point that I don't believe could ever happen, due to the expansion of memory, and the ways that it could be manipulated these days, but it seems as if it may have been an issue before, if I'm not mistaken.

Summary: Is there a way to manage non dynamic data directly, allocate it to the stack, and remove it from the stack through a function call, or is this completely run by the programs internal instructions?

Example:

void foo(){

  short int operator;
  /*Did what needed to be done with the operator variable***********/
  //Pseudo-code

   delete operator;

  /*Even though it was not allocated dynamically,
    and with the use of another function call*/
}
L.P.
  • 406
  • 5
  • 17
  • Aside from the fact that your example is neither valid C nor C++, the compiler handles the stack for you. Still, there's `alloca` (freed on block-exit) and C has variable-length-arrays (don not, ever, mix with `alloca`) for making things more interesting. – Deduplicator Nov 28 '14 at 01:40
  • I know that the syntax is not viable for either C or C++ I placed it as a somewhat pseudo-coded example, in itself. Thank you for the alloca function though. Will read up on it. – L.P. Nov 28 '14 at 01:53
  • When something goes out of scope it is cleaned up automatically. Put your "stack allocated" variable in a code-block and it will be vaporised at the end of the block. Deleting local variables using the `delete` operator makes no sense. – Matt Coubrough Nov 28 '14 at 01:55

1 Answers1

3

As you said, easy way of doing this would just be to put variable in lower scope and allow it to free itself.

If it's any container, you can clear it with appropriate function call.

Basically:

delete what you new, delete[] what you new[].

Also see this: https://stackoverflow.com/a/441837/2975193

Community
  • 1
  • 1
Patryk Krawczyk
  • 1,342
  • 1
  • 14
  • 25
  • Just noticed the possibility of placing it within it's own scope, and declaring everything else outside of it. That escaped me in itself. I tend to think of over-complicating simple points too much. gotta remember to follow the KISS principle a bit more. – L.P. Nov 28 '14 at 01:51