|
18 | 18 |
|
19 | 19 | #include "new.h"
|
20 | 20 |
|
| 21 | +// The C++ spec dicates that allocation failure should cause the |
| 22 | +// (non-nothrow version of the) operator new to throw an exception. |
| 23 | +// Since we expect to have exceptions disabled, it would be more |
| 24 | +// appropriate (and probably standards-compliant) to terminate instead. |
| 25 | +// Historically failure causes null to be returned, but this define |
| 26 | +// allows switching to more robust terminating behaviour (that might |
| 27 | +// become the default at some point in the future). Note that any code |
| 28 | +// that wants null to be returned can (and should) use the nothrow |
| 29 | +// versions of the new statement anyway and is unaffected by this. |
| 30 | +// #define NEW_TERMINATES_ON_FAILURE |
| 31 | + |
21 | 32 | namespace std {
|
| 33 | + // Defined in abi.cpp |
| 34 | + void terminate(); |
| 35 | + |
22 | 36 | const nothrow_t nothrow;
|
23 | 37 | }
|
24 | 38 |
|
25 |
| -void * operator new(size_t size) { |
| 39 | +static void * new_helper(size_t size) { |
26 | 40 | // Even zero-sized allocations should return a unique pointer, but
|
27 | 41 | // malloc does not guarantee this
|
28 | 42 | if (size == 0)
|
29 | 43 | size = 1;
|
30 | 44 | return malloc(size);
|
31 | 45 | }
|
| 46 | + |
| 47 | +void * operator new(size_t size) { |
| 48 | + void *res = new_helper(size); |
| 49 | +#if defined(NEW_TERMINATES_ON_FAILURE) |
| 50 | + if (!res) |
| 51 | + std::terminate(); |
| 52 | +#endif |
| 53 | + return res; |
| 54 | +} |
32 | 55 | void * operator new[](size_t size) {
|
33 | 56 | return operator new(size);
|
34 | 57 | }
|
35 | 58 |
|
36 | 59 | void * operator new(size_t size, const std::nothrow_t tag) noexcept {
|
| 60 | +#if defined(NEW_TERMINATES_ON_FAILURE) |
| 61 | + // Cannot call throwing operator new as standard suggests, so call |
| 62 | + // new_helper directly then |
| 63 | + return new_helper(size); |
| 64 | +#else |
37 | 65 | return operator new(size);
|
| 66 | +#endif |
38 | 67 | }
|
39 | 68 | void * operator new[](size_t size, const std::nothrow_t& tag) noexcept {
|
| 69 | +#if defined(NEW_TERMINATES_ON_FAILURE) |
| 70 | + // Cannot call throwing operator new[] as standard suggests, so call |
| 71 | + // malloc directly then |
| 72 | + return new_helper(size); |
| 73 | +#else |
40 | 74 | return operator new[](size);
|
| 75 | +#endif |
41 | 76 | }
|
42 | 77 |
|
43 | 78 | void * operator new(size_t size, void *place) noexcept {
|
|
0 commit comments