Difference between new operator in C++ and new operator in java

后端 未结 5 1333
粉色の甜心
粉色の甜心 2020-12-09 06:06

As far as I know, the new operator does the following things: (please correct me if I am wrong.)

  1. Allocates memory, and then returns the reference
5条回答
  •  佛祖请我去吃肉
    2020-12-09 06:27

    You seem to have the operation of new correct in that it allocates and initializes memory.

    Once the new completes successfully, you, the programmer, are responsible for deleteing that memory. The best way to make sure that this happens is to never use new directly yourself, instead preferring standard containers and algorithms, and stack-based objects. But if you do need to allocate memory, the C++ idiom is to use a smart pointer like unique_ptr from C++11 or shared_ptr from boost or C++11. That makes sure that the memory is reclaimed properly.

    If an allocation fails, the new call will throw an exception after cleaning up any portion of the object that has been constructed prior to the failure. You can use the (nothrow) version of new to return a null pointer instead of throwing an exception, but that places even more burden of cleanup onto the client code.

提交回复
热议问题