问题
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?
回答1:
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
- A specification for the alignment of the returned pointer.
- The size of the aligned block.
- A pointer to allocated memory.
- The amount of the allocated memory.
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.
来源:https://stackoverflow.com/questions/27534403/struggling-with-alignas-syntax