using new and delete
new(std::nothrow)
可以避免 memory 不夠時std::bad_alloc
exception 被丟出。我們只需要檢查得到的 pointer 是否為nullptr
即可。
比較
new & delete | malloc() & free() |
---|---|
It is an operator. | It is a library function. |
It (de)allocates the memory dynamically. | It create/destroys the memory at runtime. |
It should only be used for deallocating the memory allocated either using the new operator or for a NULL pointer. | It should only be used for deallocating the memory allocated either using malloc(), calloc(), realloc() or for a NULL pointer. |
This operator calls the destructor before it destroys the allocated memory. | This function only frees the memory from the heap. It does not call the destructor. |
It is comparatively slower because it invokes the destructor for the object being deleted before deallocating the memory. | It is faster than delete operator. |
new returns appropriate pointer | malloc returns void * and pointer needs to typecast to appropriate type. |
Output:
可看到使用 malloc 和 free 並不會 call class object 的 constructor 和 destructor。
Constructor and Destructor on the stack
當使用 exit(0) 時,只有 Constructor is called! 的 output,使用 return 0 時,Destructor is called! 也會被輸出。