本文介绍了struct __declspec(align(16))sse_t和struct alignas(16)sse_t有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct __declspec(align(16)) sse_t{};struct alignas(16) sse_t{};有什么区别?

链接到C ++ 11中的结构对齐示例: http: //en.cppreference.com/w/cpp/language/alignas

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];

但是,MSVS2012中没有关键字alignas(16),但是您可以使用__declspec(align(16)):我们可以在示例中看到的内容:

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. 这些对齐功能是否等效?
  2. 如果是这样(等效),为什么没有在MSVS2012中输入关键字alignas(),因为此功能已经存在__declspec(align(16))?
  3. 如果这样的结构通过"placement new"(新放置)放置在未对齐的地址上会发生什么?
  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)?

推荐答案

  1. 据我所知它们是等效的,区别在于struct alignas(16) sse_t{};是标准C ++,而struct __declspec(align(16)) sse_t{};是C ++ 11之前的Microsoft扩展.
  2. Microsoft尚未在MSVS2012的编译器中实现alignas()的功能,您必须问他们为什么. 我是骗子, MSVS2013仍不支持alignas/alignof .
  3. 如果这种结构未对齐,可能会发生可怕的事情.您甚至不需要放置new即可,普通的new不需要对齐要求,而对于C ++ 11而言是原始类型所需的.
  1. To my knowledge they are equivalent, the difference being that struct alignas(16) sse_t{}; is standard C++ and struct __declspec(align(16)) sse_t{}; is a pre-C++11 Microsoft extension.
  2. Microsoft hadn't gotten around to implementing alignas() in their compiler in MSVS2012, you'd have to ask them why. I'm a liar, MSVS2013 still does not support alignas / alignof.
  3. Horrible things will likely happen if such a structure is misaligned. You don't even need placement new to do so, plain old new is oblivious to alignment requirements beyond those needed for primitive types as of C++11.

这篇关于struct __declspec(align(16))sse_t和struct alignas(16)sse_t有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:43