Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

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

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 special interest due to their portability and similarity: malloc and ::operator new.

Are there any differences (w.r.t. the standard and implementation) between the global void* operator new(size_t, ::std::nothrow&) and void* malloc(size_t)?

Since there seems to be some confusion what I am talking about, consider the following two calls:

void* p = ::std::malloc(10);
void* q = ::operator new(10, ::std::nothrow);

The obvious and trivial difference is how to deallocate the memory:

::std::free(p);
::operator delete(q);

Note: This question is not a duplicate of e.g. What is the difference between new/delete and malloc/free? since it talks about using the global operator new that does not actually perform any ctor calls.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...