Rule A18-5-10 (required, implementation, automated)
Placement new shall be used only with properly aligned pointers to sufficient storage capacity.
Rationale
Placement new can be useful for cases in which allocation is required separately from type initialization, e.g. memory allocators, generic containers. Correct usage of placement new requires passing a pointer that: is suitably aligned provides sufficient storage memory Violating above constrains will result in an object constructed at a misaligned location or memory initialization outside of the allocated bounds, which leads to undefined behaviour. An initial memory pointer used for placement new shall not be used after the call.
Example
//% $Id: A18-5-10.cpp 305629 2018-01-29 13:29:25Z piotr.serwa $
#include <new>
#include <cstdint>
void Foo()
{
uint8_t c;
uint64_t* ptr = ::new (&c) uint64_t;
//non-compliant, insufficient storage
}
void Bar()
{
uint8_t c; // Used elsewhere in the function
uint8_t buf[sizeof(uint64_t)];
uint64_t* ptr = ::new (buf) uint64_t;
//non-compliant, storage not properly aligned
}
See also
SEI CERT C++ Coding Standard [10]: MEM54-CPP: Provide placement new with properly aligned pointers to sufficient storage capacity Rule A18-5-11 (required, implementation, automated) “operator new” and “operator delete” shall be defined together.
Rationale
Providing a custom allocation function (operator new) for a class or program implies the use of a custom memory management scheme different to the default one. It is therefore unlikely that memory allocated using a custom allocation function can be deallocated by the default deallocation function (operator delete).
Example
//% $Id: A18-5-11.cpp 316977 2018-04-20 12:37:31Z christof.meerwald $
#include <cstdlib>
class A {
public:
static void * operator new(std::size_t s); // Compliant: operator new
static void operator delete(void *ptr);
// defined together with
// operator delete
};
class B {
public:
static void * operator new(std::size_t s);
// Non-compliant: operator
static void * operator new [](std::size_t s); // new defined without
// corresponding operator
// delete
};
See also
HIC++ v4.0 [9]: 12.3.1: Correctly declare overloads for operator new and delete