I am trying to use alignas
for pointers that are class members, and frankly I am not sure where I supposed to put it.
For instance:
class A
{
private:
int n;
alignas(64) double* ptr;
public:
A(const int num) : n(num), ptr(new double[num])
{}
};
which I hoped would ensure the data for ptr was aligned on a 64-byte block. Using the Intel compiler, it doesn't.
Can anyone point me in the right direction please?
The alignas type specifier is a portable, C++ standard way to specify custom alignment of variables and user defined types. The alignof operator is likewise a standard, portable way to obtain the alignment of a specified type or variable.
In C++11 the alignof operator used to returns the alignment, in bytes of the specified type. Syntax: alignof(type) Syntax Explanation: alignof: operator returns the alignment in byte, required for instances of type, which type is either complete type, array type or a reference type.
Using the alignas(N)
keyword on a member of a class causes this member to be aligned according to the specified alignment, not any entity potentially pointed to. After all, when initializing a pointer with a value there is no control to align the already existing objects.
You might want to have a look at std::align()
which takes
It returns a correspondingly aligned pointer unless there is not enough space to satisfy both the alignment and size requirements. If thereis not enought space the function return a null pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With