Skip to content

Commit b53ff89

Browse files
committed
doc
1 parent 146d1f5 commit b53ff89

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

doc/reference.rst

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,21 @@ C++
221221

222222
- About C++ ``operator new`` and return value and its replacement ``new0<>()``
223223

224+
In short, it is preferred for stability to use new `new0` instead of `new`:
225+
226+
.. code:: cpp
227+
228+
SomeClass* sc = new0<SomeClass>(arg1, arg2, ...);
229+
// abort() is never called, an exception is not thrown even if they are enabled
230+
if (sc == nullptr)
231+
{
232+
// failed allocation, handle here
233+
}
234+
else
235+
{
236+
// use sc
237+
}
238+
224239
The C++ standard says the following about the ``new`` operator behavior when encountering heap shortage (memory full):
225240

226241
- has to throw a ``std::bad_alloc`` C++ exception
@@ -235,7 +250,7 @@ C++
235250

236251
- guarantee that any subobjects partially constructed get destroyed, and in the correct order, if oom is encountered midway through construction
237252

238-
When C++ exceptions are disabled, or when using new(nothrow), the above guarantees can't be upheld, so the second point above is the only viable solution.
253+
When C++ exceptions are disabled, or when using ``new(nothrow)``, the above guarantees can't be upheld, so the second point above is the only viable solution.
239254

240255
Historically in Arduino environments, ``new`` is overloaded to simply return the equivalent ``malloc()`` which in turn can return ``nullptr``. In other cores, and up to our core version 2.5.2, that is considered as acceptable.
241256

0 commit comments

Comments
 (0)