knightyangpku
knightyangpku

Reputation: 77

Memory alignment syntax in C++

What determines C/C++ Memory Alignment Syntax?

I am working on some embedded application, which requires memory/data alignment. From my previous experience, for C code, with GCC and MSVC, the memory alignment syntax seems to be mainly determined by the compiler:

GCC   __attribute__ ((aligned (128)))
MSVC   __declspec(align(128))

I am curious about the following questions:

  1. Does the alignment syntax also depend on other factors, such as target hardware and/or data model of OS? Or is it solely dependent on the compiler?
  2. For C++11, is the new syntax alignas(128) part of the C++11 standard and thus independent of compiler/platform?
  3. For C++11, when we use std::align on data, will it do a full data copy and thus hinder the performance?

Upvotes: 1

Views: 744

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117831

  1. The syntax doesn't change depending on what the target is.
  2. Yes, alignas is a C++ keyword since C++11, but note:

    If the strictest (largest) alignas on a declaration is weaker than the alignment it would have without any alignas specifiers (that is, weaker than its natural alignment or weaker than alignas on another declaration of the same object or type), the program is ill-formed

    Since types have different alignments on different platforms, this may work for one target platform and fail for another:

    struct alignas(2) foo { int bar; };
    
  3. No, std::align does not copy data. It modifies a pointer and a size_t space counter if needed.

    If the buffer is too small, the function does nothing and returns nullptr

Upvotes: 1

Related Questions