Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does gcc warn about large alignas value?

Tags:

c++

c++14

When compiled with gcc 6.3, this example program

#include <array>

class alignas(4096) A {
    std::array<int, 256> array;
};

int main()
{
    A a;
}

gives the following warning:

3 : <source>:3:21: warning: requested alignment 4096 is larger than 128 [-Wattributes]
 class alignas(4096) A {
                     ^

There's no such error with gcc 7.2 though.

Example

  1. Does it mean that the compiler just informs about alignment being too big? What's the purpose of such a warning?
  2. The standard doesn't allow the compiler to ignore this alignment specifier (even in presence of the warning), does it?
like image 942
Dev Null Avatar asked Jan 03 '18 02:01

Dev Null


1 Answers

The standard allows all sorts of things to break if you alignas to larger than that of std::max_align_t:

the largest fundamental alignment of any type is the alignment of std::max_align_t. If a type's alignment is made stricter (larger) than std::max_align_t using alignas, it is known as a type with extended alignment requirement. A type whose alignment is extended or a class type whose non-static data member has extended alignment is an over-aligned type. It is implementation-defined if new-expression, std::allocator::allocate, and std::get_temporary_buffer support over-aligned types. Allocators instantiated with over-aligned types are allowed to fail to instantiate at compile time, to throw std::bad_alloc at runtime, to silently ignore unsupported alignment requirement, or to handle them correctly.

Basically, you can declare highly aligned types, but some stuff might break when you use them; it's possible GCC6 is being conservative, or it might actually fail for some of the specified cases mentioned above and it's trying to warn you.

like image 183
ShadowRanger Avatar answered Nov 12 '22 13:11

ShadowRanger