cpp: new: Add no-throwing implementation of new operator

C++ subsystem defines exception throwing operator new.
Though the implementation never throws an exception.

If used by an application it should verify if requested
memory was allocated. This is against C++ standard.
If an application does not support exceptions or does not
want to call throwing new operator, it should use a
specialization of a new operator that makes sure it
never throws bad_alloc exception. The cpp subsystem
does not provide this specialization.

The commit adds missing operator new specializations.

Signed-off-by: Piotr Pryga <piotr.pryga@nordicsemi.no>
This commit is contained in:
Piotr Pryga 2022-09-15 18:26:05 +02:00 committed by Carles Cufí
commit a0dc682bd9
2 changed files with 39 additions and 0 deletions

View file

@ -22,6 +22,16 @@ void* operator new[](size_t size)
return malloc(size);
}
void* operator new(std::size_t size, const std::nothrow_t& tag) NOEXCEPT
{
return malloc(size);
}
void* operator new[](std::size_t size, const std::nothrow_t& tag) NOEXCEPT
{
return malloc(size);
}
void operator delete(void* ptr) NOEXCEPT
{
free(ptr);

29
subsys/cpp/include/new Normal file
View file

@ -0,0 +1,29 @@
/*
* Copyright 2022 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file
*
* @brief Stub header allowing compilation of `#include <new>`
*/
#ifndef ZEPHYR_SUBSYS_CPP_INCLUDE_NEW_
#define ZEPHYR_SUBSYS_CPP_INCLUDE_NEW_
#include <cstddef>
namespace std {
#if __cplusplus < 201103L
struct nothrow_t {};
#else
struct nothrow_t {
explicit nothrow_t() = default;
};
#endif /* __cplusplus */
extern const std::nothrow_t nothrow;
}
#endif /* ZEPHYR_SUBSYS_CPP_INCLUDE_NEW_ */