简体   繁体   中英

What dynamic memory used for?(C++)

I read about C++ dynamic memory allocation. Here is my code:

 #include <iostream>
 using namespace std;
 int main()
 {
    int t;
    cin>>t;
    int a[t];
    return 0;
 }

What is the difference between the above and the following:

int* a=new(nothrow) int[t];

Use dynamic allocation:

  • when you need control over when an object is created and destroyed; or
  • when you need to create a local object that's too big to risk putting on the stack; or
  • when the size of a local array isn't a constant

To answer your specific question: int a[t]; isn't valid C++, since an array size must be constant. Some compilers allow such variable-length arrays as an extension, borrowed from C; but you shouldn't use them, unless you don't mind being tied to that compiler.

So you'd want dynamic allocation there, either the easy way, managed by RAII :

std::vector<int> a(t);
// use it, let it clean itself up when it goes out of scope

or the hard way, managed by juggling pointers and hoping you don't drop them:

int* a=new int[t];
// use it, hope nothing throws an exception or otherwise leaves the scope
delete [] a; // don't forget to delete it

Your first example is C99-compatible array allocations, which occur on the stack and whose lifetimes are similar to other local variables.

The allocation example is a typical C++ dynamic memory allocation, which occurs from the heap and whose lifetime extends until delete a[] is reached--without this code the memory is "leaked". The one-of-lifetime occurs with the variable is destructed by delete and can occur after the current local scope has ended.

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