Which to use - “operator new” or “operator new[]” - to allocate a block of raw memory in C++?

后端 未结 4 1145
情话喂你
情话喂你 2021-01-12 05:54

My C++ program needs a block of uninitialized memory and a void* pointer to that block so that I can give it to a third party library. I want to pass control of

4条回答
  •  终归单人心
    2021-01-12 06:34

    The advantage of the C++ new operators over C's malloc() and free() is that the former throws an exception if there is not enough memory, rather than returning NULL.

    Regarding choosing new(size) and new[] for character buffers, I'd advocate the latter since it is less likely to surprise people maintaining the code later i.e. char* buf = new char[size] and delete[] buf.

    The values in the buffer will not be initialised, and there is no range-checking - you have to build a nice C++ object to do that for you, or use an existing object such as std::vector or std::string.

提交回复
热议问题