Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

...

[ISO/IEC 14882-2014]

18.6.1.1, "Single-object Forms"
18.6.1.2, "Array Forms"
20.7.9.1, "Allocator Members"

[ISO/IEC 9899:2011]Section 7.20.3, "Memory management functions"
[Meyers 95]Item 7. Be prepared for out-of-memory conditions.
[Seacord 2013b]Chapter 4, "Dynamic Memory Management"

 

MEM31-CPP. Free dynamically allocated memory exactly once      08Image Added      008. Memory Management (MEM)      MEM33-CPP. Ensure that aborted constructors do not leakImage Added