C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fwd: set_new_handler extension

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Mon, 20 Feb 2023 22:09:33 +0000
On Mon, Feb 20, 2023 at 7:51 PM Julien Villemure-Fr├ęchette via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> global operator new and delete can be replaced by a non inline, non static global operator new with equivalent signature


I wrote a program one time and I wanted it to be lightning fast, and
so I overloaded 'new' so that it allocated massive chunks at a time,
and 'delete' didn't do anything. I of course was wasting memory but it
was fine as I had enough RAM. Here's what I did:

#include <cstddef> // size_t
#include <cstdlib> // malloc
#include <new> // required otherwise we get a compiler error
for the 'noexcept'

using std::size_t;

size_t g_total_allocation = 0u;

inline void *Implementation_Global_New(size_t size) noexcept
{
    size += 8u - (size % 8u);

    static size_t constexpr bytes_at_a_time = 10485760u; /* We
allocate 10 megabytes at a time */

    if ( size > bytes_at_a_time ) return nullptr;

    static void *p = nullptr;

    static size_t bytes_allocated_so_far = 0u;

    for (; /* ever */ ;)
    {
        if ( nullptr == p )
        {
            p = std::malloc(bytes_at_a_time);

            if ( nullptr == p ) return nullptr;

            g_total_allocation += bytes_at_a_time;
        }

        if ( (bytes_allocated_so_far + size) > bytes_at_a_time )
        {
            p = nullptr;

            bytes_allocated_so_far = 0u;
        }
        else
        {
            break;
        }
    }

    void *const retval = static_cast<char*>(p) + bytes_allocated_so_far;

    bytes_allocated_so_far += size;

    return retval;
}

void *operator new (size_t const size) noexcept { return
Implementation_Global_New(size); }
void *operator new[](size_t const size) noexcept { return
Implementation_Global_New(size); }
void operator delete (void *const p) noexcept { /* Do Nothing */ }
void operator delete[](void *const p) noexcept { /* Do Nothing */ }

Received on 2023-02-20 22:09:41