3

What is the difference between struct __declspec(align(16)) sse_t{}; and struct alignas(16) sse_t{};?

Link to an example of the alignment of structures in C++11: http://en.cppreference.com/w/cpp/language/alignas

// every object of type sse_t will be aligned to 16-byte boundary
struct alignas(16) sse_t
{
  float sse_data[4];
};

// the array "cacheline" will be aligned to 128-byte boundary
alignas(128) char cacheline[128];

However, there is not in MSVS2012 keyword alignas(16), but you can use __declspec(align(16)): Where can I use alignas() in C++11? What we can see in example:

#include <iostream>

#ifdef __GNUC__
struct __attribute__(align(16)) sse_t
#else
struct __declspec(align(16)) sse_t
#endif
{
  float sse_data[4];
};

/*
// Why doesn't it support in MSVS 2012 if it is the same as __declspec(align(16)) ?
struct alignas(16) sse_t
{
  float sse_data[4];
};
*/    

int main() {
    // aligned data
    sse_t ab;
    ab.sse_data[1] = 10;

    // what will happen?
    unsigned char *buff_ptr = new unsigned char [1000]; // allocate buffer
    sse_t * unaligned_ptr = new(buff_ptr + 3) sse_t;    // placement new
    unaligned_ptr->sse_data[1] = 20;    

    int b; std::cin >> b;
    return 0;
}
  1. These functionalities of alignment are equivalent?
  2. And if so - equivalent, why did not entered keyword alignas() in MSVS2012, because this functionality is already there __declspec(align(16))?
  3. And what will happen if such a structure to place on a misaligned address through "placement new": new(buff_ptr + 3)?
4

1 回答 1

4
  1. 据我所知,它们是等价的,区别在于struct alignas(16) sse_t{};标准 C++ 和struct __declspec(align(16)) sse_t{};C++11 之前的 Microsoft 扩展。
  2. 微软还没有alignas()在他们的编译器中实现 MSVS2012,你必须问他们为什么。IIRC 它在 MSVS2013 中受支持。编辑:我是个骗子,MSVS2013 仍然不支持alignas/alignof
  3. 如果这样的结构错位,很可能会发生可怕的事情。你甚至不需要放置new来这样做,plain oldnew忽略了超出 C++11 原始类型所需的对齐要求。
于 2013-11-13T16:25:21.373 回答