...
By default operator new
will throw a std::bad_alloc
exception if the allocation fails. Therefore you need not check that the result of operator new
is NULL
. However, to ease conversion of code to C++, the C++ Standard ISO/IEC 14882-2003 provides a variant of operator new
that behaves like malloc()
:
Code Block |
---|
int* s = new int[-1]; // throws a std::bad_alloc exception
int* s = new (std::nothrow) int[-1]; // returns NULL
|
...
- Setting
errno
is a POSIX ® extension to C99.
In addition, operator new[]
can throw an error of type std::bad_array_new_length
if the size
argument passed to new
is negative or excessively large. This is a subclass of std::bad_alloc
.
Noncompliant Code Example (malloc()
)
...
Code Block |
---|
|
void f(const int *array, std::size_t size) {
int* copy = (int*)std::malloc(size * sizeof *copy);
std::memcpy(copy, array, size * sizeof *copy);
// ...
free(copy);
}
|
...
Code Block |
---|
|
void f(const int* array, std::size_t size) {
int* copy = new(std::nothrow) int[size];
std::memcpy(copy, array, size * sizeof *copy);
// ...
delete[] copy;
}
|
...
Code Block |
---|
|
int f(const int* array, std::size_t size) {
int* const copy = new(std::nothrow) int[size];
if (copy == NULL) {
// Indicate error to caller.
return -1;
}
std::memcpy(copy, array, size * sizeof *copy);
// ...
delete[] copy;
// Indicate successful completion.
return 0;
}
|
...
Code Block |
---|
|
int f(const int* array, std::size_t size) {
int* copy;
try {
copy = new int[size];
}
catch (std::bad_alloc&) {
// Indicate error to caller.
return -1;
}
std::memcpy(copy, array, size * sizeof *copy);
// ...
delete[] copy;
// Indicate successful completion.
return 0;
}
|
...