Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ alignment - strict and weak

I'm reading N3485 C++ Standard Draft and in the section on alignment, it states the following:

3.11 Alignment [basic.align]

1 ... An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated. An object type imposes an alignment requirement on every object of that type; stricter alignment can be requested using the alignment specifier (7.6.2).

Here it states what alignment is, and I get that. It means that if you have 32 bit (4byte) system, it will read in 4 byte size chunks at a time, so you should place things in memory at 4 byte offset addresses. A lot of this is handled by a good compiler, however C++ lets you have your say in it too.

The alignment-specifier it speaks of is alignas.

You can pass an integer to alignas to specify your alignment requirement or a type like alignas(double)

Now, you have weak or strict alignment, which is stated to be the following:

5 Alignments have an order from weaker to stronger or stricter alignments. Stricter alignments have larger alignment values. An address that satisfies an alignment requirement also satisfies any weaker valid alignment requirement.

7 Comparing alignments is meaningful and provides the obvious results:

— Two alignments are equal when their numeric values are equal.

— Two alignments are different when their numeric values are not equal.

When an alignment is larger than another it represents a stricter alignment.

So here it states that a stricter alignment is a larger alignment. Does that just mean that alignas(8) is more strict than alignas(4)? On a 32 bit (4 byte) system, the 8 version would mean that int type would require two reads instead of one, and one with just padding. Is the strict referring to the fact that it imposes potential overhead on the CPU, when alignment is "misused", as in this silly example?

I realize that not all alignments are valid on a given system, and that extended alignments have to be valid in order to produce correct behavior.

To me alignment is about letting the CPU access memory data in word size chunks, which is the most optimal way for a CPU to fetch and write data to and from memory.

This strict alignment, as I understand it, could potentially ruin that. Am I wrong? What is strict alignment vs weak alignment?

like image 894
Tony The Lion Avatar asked Apr 05 '13 12:04

Tony The Lion


1 Answers

The "strict" merely refers to the fact that larger alignment values are more restrictive in terms of the possible addresses.

There are only half as many valid addresses for alignment 8 as there are for alignment 4, so a type with alignment 8 is more restricted regarding where it can be placed.

like image 62
R. Martinho Fernandes Avatar answered Nov 08 '22 17:11

R. Martinho Fernandes