new expression - cppreference.com
Creates and initializes objects with dynamic storage duration, that is, objects whose lifetime is not necessarily limited by the scope in which they were created.
Syntax
::(optional) new ( type ) initializer(optional) (1)
::(optional) new new-type initializer(optional) (2)
::(optional) new (placement-params) ( type ) initializer(optional) (3)
::(optional) new (placement-params) new-type initializer(optional) (4)
\1) Attempts to create an object of type, denoted by the type-id type, which may be array type, and may include a placeholder type specifier (since C++11), or include a class template name whose argument is to be deduced by class template argument deduction (since C++17).
\2) Same as (1), but new-type cannot include parentheses:
new int(*[10])(); // error: parsed as (new int) (*[10]) ()
new (int (*[10])()); // okay: allocates an array of 10 pointers to functions
new int + 1; // okay: parsed as (new int) + 1, increments a pointer returned by new int
new int * 1; // error: parsed as (new int*) (1)
\3) Same as (1), but provides additional arguments to the allocation function, see placement new.
\4) Same as (2), but provides additional arguments to the allocation function.
placement new
If placement-params
are provided, they are passed to the allocation function as additional arguments. Such allocation functions are known as “placement new”, after the standard allocation function void* operator new(std::size_t, void*), which simply returns its second argument unchanged. This is used to construct objects in allocated storage:
// within any block scope...
{
// Statically allocate the storage with automatic storage duration
// which is large enough for any object of type `T`.
alignas(T) unsigned char buf[sizeof(T)];
T* tptr = new(buf) T; // Construct a `T` object, placing it directly into your
// pre-allocated storage at memory address `buf`.
tptr->~T(); // You must **manually** call the object's destructor
// if its side effects is depended by the program.
} // Leaving this block scope automatically deallocates `buf`.
c++17的一些说明本文未记录
举例
new(visitLists[a]) Bitset[subgraphSize]();
在visitLists[a]
这个地址开始处的内存处,构造一个类型为Bitset[subgraphSize]
的object
std::array<Bitset*,2> visitLists;
for(int a=0; a<2; a++) {
//分配内存
//int posix_memalign(void **__memptr, size_t __alignment, size_t __size)
//Allocate memory of SIZE bytes with an alignment of ALIGNMENT, return a pointer to the allocated memory in memptr
//Upon successful completion(return 0), the value pointed to by memptr shall be a multiple of alignment.
const auto ret=posix_memalign(reinterpret_cast<void**>(&(visitLists[a])),64,sizeof(Bitset)*subgraphSize);
if(unlikely(ret!=0)) { //告诉编译器ret!=0很可能为假 //#define unlikely(x) __builtin_expect(!!(x), 0)
throw -1;
}
//构造
new(visitLists[a]) Bitset[subgraphSize](); //create an object of type `Bitset[subgraphSize]`, through calling () constructor,
//directly into storage at memory address `visitLists[a]`.
}