【问题标题】:gcc alignas issue with member pointers to objectsgcc alignas 问题与指向对象的成员指针
【发布时间】:2016-07-30 03:36:32
【问题描述】:

我正在使用 gcc 4.9.2,并且正在尝试正确对齐静态初始化的数组以用于 AVX。以下是由于对齐问题而导致段错误的代码要点:

#include <iostream>
#include <cstddef>

struct B {
    alignas(32) double x[1] = {0};
};

struct A
{
    A() { b1 = new B(); b2 = new B(); }

    B* b1;
    B* b2;
};

int main(int argc, char** argv) {
    A a;

    int ret = (ptrdiff_t) a.b1->x % 32 + (ptrdiff_t) a.b2->x % 32;

    std::cout << (ptrdiff_t) a.b1->x % 32 << "," << (ptrdiff_t) a.b2->x % 32 << "\n";

    return ret;
}

在我的系统上,数组 a.b2->x 未在 32 字节边界上对齐。 x 的大小无关紧要,只要 x 是一个数组即可(因此“double x = 0”可以正常工作)。如果我改为将指针指向 B 静态分配的成员,则它可以正常工作。如果我在 main 中创建局部变量 *b1 和 *b2,它可以正常工作。如果我在 A 类和 posix_memalign 中使用动态分配的数组,它可以正常工作。

我对 alignas 有什么误解吗?

【问题讨论】:

    标签: c++ c++11 memory-alignment alignas


    【解决方案1】:

    如果我理解正确,来自以下文档

    http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3396.htm

    new 不需要尊重alignas

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2014-01-02
    • 2016-02-25
    • 2021-06-06
    • 2023-02-09
    • 1970-01-01
    相关资源
    最近更新 更多