|
1 |
| -// BAD: on memory allocation error, the program terminates. |
2 |
| -void badFunction(const int *source, std::size_t length) noexcept { |
3 |
| - int * dest = new int[length]; |
| 1 | +// BAD: the allocation will throw an unhandled exception |
| 2 | +// instead of returning a null pointer. |
| 3 | +void bad1(std::size_t length) noexcept { |
| 4 | + int* dest = new int[length]; |
| 5 | + if(!dest) { |
| 6 | + return; |
| 7 | + } |
4 | 8 | std::memset(dest, 0, length);
|
5 |
| -// .. |
| 9 | + // ... |
6 | 10 | }
|
7 |
| -// GOOD: memory allocation error will be handled. |
8 |
| -void goodFunction(const int *source, std::size_t length) noexcept { |
| 11 | + |
| 12 | +// BAD: the allocation won't throw an exception, but |
| 13 | +// instead return a null pointer. |
| 14 | +void bad2(std::size_t length) noexcept { |
9 | 15 | try {
|
10 |
| - int * dest = new int[length]; |
11 |
| - } catch(std::bad_alloc) { |
| 16 | + int* dest = new(std::nothrow) int[length]; |
| 17 | + std::memset(dest, 0, length); |
| 18 | + // ... |
| 19 | + } catch(std::bad_alloc&) { |
12 | 20 | // ...
|
13 | 21 | }
|
14 |
| - std::memset(dest, 0, length); |
15 |
| -// .. |
16 | 22 | }
|
17 |
| -// BAD: memory allocation error will not be handled. |
18 |
| -void badFunction(const int *source, std::size_t length) noexcept { |
| 23 | + |
| 24 | +// GOOD: the allocation failure is handled appropiately. |
| 25 | +void good1(std::size_t length) noexcept { |
19 | 26 | try {
|
20 |
| - int * dest = new (std::nothrow) int[length]; |
21 |
| - } catch(std::bad_alloc) { |
| 27 | + int* dest = new int[length]; |
| 28 | + std::memset(dest, 0, length); |
| 29 | + // ... |
| 30 | + } catch(std::bad_alloc&) { |
22 | 31 | // ...
|
23 | 32 | }
|
24 |
| - std::memset(dest, 0, length); |
25 |
| -// .. |
26 | 33 | }
|
27 |
| -// GOOD: memory allocation error will be handled. |
28 |
| -void goodFunction(const int *source, std::size_t length) noexcept { |
29 |
| - int * dest = new (std::nothrow) int[length]; |
30 |
| - if (!dest) { |
31 |
| - return; |
| 34 | + |
| 35 | +// GOOD: the allocation failure is handled appropiately. |
| 36 | +void good2(std::size_t length) noexcept { |
| 37 | + int* dest = new int[length]; |
| 38 | + if(!dest) { |
| 39 | + return; |
32 | 40 | }
|
33 | 41 | std::memset(dest, 0, length);
|
34 |
| -// .. |
| 42 | + // ... |
35 | 43 | }
|
0 commit comments