Struggling with alignas syntax

2k Views Asked by At

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

There are 1 best solutions below

4
On BEST ANSWER

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

  1. A specification for the alignment of the returned pointer.
  2. The size of the aligned block.
  3. A pointer to allocated memory.
  4. 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.