Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struggling with alignas syntax

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?

like image 903
user1683586 Avatar asked Dec 17 '14 20:12

user1683586


People also ask

What is alignas in c++?

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.

What is Alignof?

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.


1 Answers

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.

like image 106
Dietmar Kühl Avatar answered Oct 11 '22 07:10

Dietmar Kühl