简体   繁体   中英

Globaly replace all new operators

I'm using an RTOS in an (embedded) C++ application. Since i'm working on an embedded target i try to keep the heap allocations to a minimum. However at some point STL classes like vector come in very handy.

Because i'm using a RTOS, i have to make sure that the new/malloc() call is thread safe. Luckyly my RTOS (FreeRTOS) provides it's own (threadsafe) malloc() routines. I only do have to use them.

So far i implemented the following new/delete pair and linked it into the binary.

void * operator new(size_t n) noexcept(false);


void operator delete(void * p) noexcept(true);


void operator delete(void * p, size_t n) noexcept(true);

However looking at this

https://en.cppreference.com/w/cpp/memory/new/operator_new

shows me a dozen overloads of new (and as many overloads for delete). Do all new or delete overloads default to my replacement or am i missing an operator overload?

The default behaviour of the standard library for many of the operator new and operator delete overloads is to forward to the "basic" versions of operator new and operator delete .

The "basic" operators are:

void* operator new (std::size_t count);
void* operator new (std::size_t count, std::align_val_t alignment); // C++17 only
void operator delete(void* ptr) noexcept;
void operator delete(void* ptr, std::align_val_t alignment) noexcept; // C++17 only

Assuming that you have a standard library implementation that implements the default behaviour as defined in the C++ standard¹, the above operators are the only ones that you need to replace.

The default behaviour was first defined in the C++11 standard, so your standard library implementation must support this at minimum.

[1]: See the section titled "Storage allocation and deallocation [new.delete]" in a C++ standard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM