简体   繁体   中英

Do I need to delete arrays explicitly in C++ for memory conservation?

In one function. I create a local arrray. char arr[20]; And before end of this function. Will compiler do garbage collection for me? Or I need to do delete by myself?

There is no Garbage Collection in C++.

However, if you use automatic variables, they will be destroyed when they fall out of scope.

As a rule, there should be 1 delete call for every new . If you have no new , you don't delete .

You don't have to delete this array since you create it on stack. If you created the array using new then you would have to use delete to clean up.

Local variables are destroyed at the end of the block (not necessarily function) in which they're created. For example:

void myfunc() { 
   int x[some_size];

   if (something) { 
       std::vector<std::string> y;
       // ...
   } // y will be destroyed here
   // more code
} // x will be destroyed here

If you want your array destroyed earlier than the exit from the function, you may want to make use of the same:

void f() { 
    // come code here   

    {
        int x[size];

         // code that uses x
    } // `x` gets destroyed here

    // more code
 }

I should add, however, that destroying the variable at that point may not affect memory usage. The memory isn't needed after you exit from the inner block, but it may not be released immediately either.

On the other hand, if you use something like std::vector instead of explicit dynamic allocation, destroying the object will (immediately) free the memory that was being used to store the object's data.

Any local variables (including arrays) are created on the stack, and therefore are reclaimed when the function returns.

You can think of this similar to garbage collection, but the details are very different. If you do more of any kind of programming, you should learn more about other languages (it is similar in most languages).

So no, you do not need to do anything with your local array.

Variables only exist within the function they're defined in. Once that function terminates, they're gone. You only need to delete / free your variables if you manually allocated the memory with a new or malloc type command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM