|
1 | | -// BAD: no memory allocation errors are detected |
2 | | -void f(const int *array, std::size_t size) noexcept { |
3 | | - int *copy = new int[size]; |
4 | | - std::memcpy(copy, array, size * sizeof(*copy)); |
5 | | - // ... |
6 | | - delete [] copy; |
| 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]; |
| 4 | + std::memset(dest, 0, length); |
| 5 | +// .. |
7 | 6 | } |
8 | | -// GOOD: memory allocation errors are detected |
9 | | -void f(const int *array, std::size_t size) noexcept { |
10 | | - int *copy; |
| 7 | +// GOOD: memory allocation error will be handled. |
| 8 | +void goodFunction(const int *source, std::size_t length) noexcept { |
11 | 9 | try { |
12 | | - copy = new int[size]; |
13 | | - } catch(std::bad_alloc) { |
14 | | - // Handle error |
15 | | - return; |
16 | | - } |
17 | | - // At this point, copy has been initialized to allocated memory |
18 | | - std::memcpy(copy, array, size * sizeof(*copy)); |
19 | | - // ... |
20 | | - delete [] copy; |
| 10 | + int * dest = new int[length]; |
| 11 | + } catch(std::bad_alloc) |
| 12 | + std::memset(dest, 0, length); |
| 13 | +// .. |
| 14 | +} |
| 15 | +// BAD: memory allocation error will not be handled. |
| 16 | +void badFunction(const int *source, std::size_t length) noexcept { |
| 17 | + try { |
| 18 | + int * dest = new (std::nothrow) int[length]; |
| 19 | + } catch(std::bad_alloc) |
| 20 | + std::memset(dest, 0, length); |
| 21 | +// .. |
21 | 22 | } |
22 | | -// GOOD: memory allocation errors are detected |
23 | | -void f(const int *array, std::size_t size) noexcept { |
24 | | - int *copy = new (std::nothrow) int[size]; |
25 | | - if (!copy) { |
26 | | - // Handle error |
27 | | - return; |
| 23 | +// GOOD: memory allocation error will be handled. |
| 24 | +void goodFunction(const int *source, std::size_t length) noexcept { |
| 25 | + int * dest = new (std::nothrow) int[length]; |
| 26 | + if (!dest) { |
| 27 | + return; |
28 | 28 | } |
29 | | - std::memcpy(copy, array, size * sizeof(*copy)); |
30 | | - // ... |
31 | | - delete [] copy; |
| 29 | + std::memset(dest, 0, length); |
| 30 | +// .. |
32 | 31 | } |
0 commit comments