Memory allocation in C++ without the 'new' keyword
This question already has an answer here:
These variables are of scope 'automatic'. The language guarantees that your program will release this storage at the end of the current block. It is probably on the stack, but nothing forces the implementation to use the stack. Bottom line: no leak.
malloc and new will allocate memory on the heap, otherwise the data in placed on the stack. Anything on the heap will need to be manually freed.
It's also worth noting that malloc and new shoudn't be mixed.
Don't use malloc for class types as this can cause problems.
anything using new should use delete, and anything using new[] should use delete[].
eg
// example of new[] and delete[]
int* ints = new int[10];
...
delete [] ints;
// example of malloc and free
int* ints = static_cast<int*>(malloc(sizeof(int) * 10));
...
free(ints);
链接地址: http://www.djcxy.com/p/40646.html
上一篇: 从Java转向C ++和新的
下一篇: C ++中没有“new”关键字的内存分配