On Fri, 6 Nov 2015, Jonathan Wakely wrote:

On 6 November 2015 at 09:02, Daniel Gutson
<daniel.gut...@tallertechnologies.com> wrote:

El 5/11/2015 22:56, "Jonathan Wakely" <jwakely....@gmail.com> escribió:

It can just call malloc, and the replacement operator delete can call
free.

It can but the actual code of operator new is optimized and more complex
(for example by using intrinsics). The user might not want to deal with the
STL implementation internals.

The code is more complex for reasons that might not apply to your code.
If you are replacing new, you don't need to look at a new handler, you
can write directly whatever code you want. If you know how malloc(0)
behaves on your platform (or are confident that you will never call new
with size 0), you can skip the initial test.

IIRC I introduced the __builtin_expect in that code, but I personnally
often write the following in my code, assuming that allocation will
never fail:
inline void* operator new(std::size_t n){return malloc(n);}
inline void operator delete(void*p)noexcept{free(p);}
(same with nothrow and arrays)

(technically illegal because of 'inline' but I don't care)

By this argument users should never replace operator new at all. I
don't find that convincing.

If they don't want to deal with implementation details then they don't
have to. The default implementations are optimized because they are
used by everyone and it would be silly to ship them without making
easy optimisations, but that doesn't mean that users have to do the
same thing in their own replacement allocation functions. Using
__builtin_expect makes a small difference when looping on the result
of malloc, but if you were to provide a replacement that doesn't loop
then the difference for a single branch is not very significant.

Actually, it is optimized for the case where it does *not* loop (gcc by
default optimizes by assuming that loops do loop).

--
Marc Glisse

Reply via email to