挣扎与alignas语法 [英] Struggling with alignas syntax

查看:251
本文介绍了挣扎与alignas语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 alignas 作为类成员的指针,坦白地说,我不知道我应该把它放在哪里。

I am trying to use alignas for pointers that are class members, and frankly I am not sure where I supposed to put it.

例如:

class A
{
private:
    int n;
    alignas(64) double* ptr;    

public:
    A(const int num) : n(num), ptr(new double[num])
    {}
};

我希望可以确保ptr的数据在64字节块上对齐。
使用英特尔编译器,它不是。

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?

推荐答案

在类的成员上使用 alignas(N)关键字会导致成员根据指定的对齐方式进行对齐,而不是任何可能指向的实体。毕竟,当使用值初始化指针时,没有控制来对齐已经存在的对象。

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.

您可能想看看 std :: align() 需要

You might want to have a look at std::align() which takes


  1. 返回指针对齐的规范。

  2. 对齐块的大小。

  3. 指向已分配内存的指针。

  4. 分配的内存量。

  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.

这篇关于挣扎与alignas语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆