...
Code Block |
---|
|
#include <cstring>
void f(const int *array, std::size_t size) noexcept {
int *copy = new int[size];
std::memcpy(copy, array, size * sizeof (*copy));
// ...
delete [] copy;
}
|
...
Code Block |
---|
|
#include <cstring>
void f(const int *array, std::size_t size) noexcept {
int *copy = new (std::nothrow) int[size];
if (!copy) {
// Handle error
return;
}
std::memcpy(copy, array, size * sizeof (*copy));
// ...
delete [] copy;
} |
...
Code Block |
---|
|
#include <cstring>
void f(const int *array, std::size_t size) noexcept {
int *copy;
try {
copy = new int[size];
} catch(std::bad_alloc) {
// Handle error
return;
}
// At this point, copy has been initialized to allocated memory.
std::memcpy(copy, array, size * sizeof (*copy));
// ...
delete [] copy;
} |
...
Code Block |
---|
|
#include <cstring>
void f(const int *array, std::size_t size) noexcept(false) {
int *copy = new int[size];
// If the allocation fails, it will throw an exception which the caller
// will have to handle.
std::memcpy(copy, array, size * sizeof (*copy));
// ...
delete [] copy;
} |
...
MEM31-CPP. Free dynamically allocated memory exactly once 08Image Added 008. Memory Management (MEM) MEM33-CPP. Ensure that aborted constructors do not leakImage Added