Difference between global non-throwing ::operator new and std::malloc

前端 未结 3 1562
一生所求
一生所求 2020-12-05 03:00

C++ has several functions to acquire dynamic storage, most of which differ in some fundamental way. Several more are usually added by the OS.

Two of these are of spe

相关标签:
3条回答
  • 2020-12-05 03:16

    The main differences, aside from syntax and free vs. delete, are

    1. you can portably replace ::operator new;
    2. malloc comes with realloc, for which new has no equivalent;
    3. new has the concept of a new_handler, for which there is no malloc equivalent.

    (Replacing malloc opens up a can of worms. It can be done, but not portably, because it requires knowledge of the linker.)

    0 讨论(0)
  • 2020-12-05 03:31

    There are two differences I can think of:

    1. Which function you must use to deallocate the memory, operator delete vs. free().

    2. A C++ program can legally provide its own version of ::operator new and that version is guaranteed to be called by new expressions. It's not possible to override malloc with your own version.

    0 讨论(0)
  • 2020-12-05 03:34

    The macroscopic difference I can see without further research is that the throwing variant of the global ::new operator throws std::bad_alloc if the allocation cannot be done, whereas malloc returns NULL. But I do believe that most of the differences listed here apply to the global ::new operator, even if the topic is about new.

    0 讨论(0)
提交回复
热议问题