Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor editorial changes

...

When using std::nothrow, the new operator returns either a null pointer or a pointer to the allocated space. Always test the returned pointer to ensure it is not nullptr before referencing the pointer. This compliant solution handles the error condition appropriately when the returned pointer is nullptr:.

Code Block
bgColor#ccccff
langcpp
#include <cstring>
#include <new>
 
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;
}

...

Alternatively, you can use ::operator new[] without std::nothrow and instead catch a std::bad_alloc exception if sufficient memory cannot be allocated:.

Code Block
bgColor#ccccff
langcpp
#include <cstring>
#include <new>
 
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;
}

...

When possible, the more resilient compliant solution is to remove the memory allocation entirely and pass the objects by reference instead:.

Code Block
bgColor#ccccff
langcpp
struct A { /* ... */ };
struct B { /* ... */ }; 
 
void g(A &a, B &b);
void f() {
  A a;
  B b;
  g(a, b);
}

...