栈:alignas
specifier (since C++11)
Specifies the alignment requirement of a type or an object.
Syntax
alignas( expression )
\1) expression must be an integral constant expression that evaluates to zero, or to a valid value for an alignment or extended alignment.
describe
The object or the type declared by such a declaration will have its alignment requirement equal to the strictest (largest) non-zero expression of all alignas
specifiers used in the declaration, unless it would weaken the natural alignment of the type.
If the strictest (largest) alignas
on a declaration is weaker than the alignment it would have without any alignas
specifiers (that is, weaker than its natural alignment or weaker than alignas
on another declaration of the same object or type), the program is ill-formed:
struct alignas(8) S {};
struct alignas(1) U { S s; }; // error: alignment of U would have been 8 without alignas(1)
Invalid non-zero alignments, such as alignas(3) are ill-formed.
Valid non-zero alignments that are weaker than another alignas on the same declaration are ignored.
alignas(0) is always ignored.
堆:posix_memalign
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
.
举例
new(visitLists[a]) Bitset[subgraphSize]();
在visitLists[a]
这个地址开始处的内存处,构造一个类型为Bitset[subgraphSize]
的object
std::array<Bitset*,2> visitLists;
for(int a=0; a<2; a++) {
//分配内存
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]`.
}