What is the "space" parameter in std::align?

Viewed 97

In https://en.cppreference.com/w/cpp/memory/align, there's a space parameter that's the "buffer size." What is meant by buffer size here?

Is it like the amount of space you have to use to create the designed alignment? If it is, why is it needed?

2 Answers

It is an input output parameter. So it will do 2 things:

  1. Tell the function how much space is available, so if alignment would overrun the buffer, the function fails:

The function modifies the pointer only if it would be possible to fit the wanted number of bytes aligned by the given alignment into the buffer. If the buffer is too small, the function does nothing and returns nullptr.

  1. Function can output how much space is left after alignment, so you can string calls together. This is useful if you were writing some sort of aligned allocator.

You have to consider why you would want to align a pointer.

Think about a case where you have a range of memory that has been allocated for you to create objects into. This is called a memory buffer. The size of the buffer is the number of bytes from the start of the range to its end. Each object has a type. Each type has an alignment requirement. Objects of that type can only be created in addresses aligned to the required byte boundary.

Let's say the first address of the memory range isn't aligned to the byte boundary that is required by the type of the object that you want to create. In such case, you cannot create the object at the beginning of the memory range. That's where you need std::align. It adjusts the given pointer to the next address that is aligned, which is the first address where the object can be created.

To do that, you only need to know the address and the alignment. But you also need to know whether the object can fit inside of your memory range after the alignment. For example, if you have 16 bytes of memory and you want to create an object of 16 bytes, but the first address isn't aligned to the 4 byte boundary so if you create the object starting from the adjusted (aligned) address, then it would overflow the memory range by the number of adjusted bytes. So in order to know that, we also pass the size of the object and the size of the memory space. If the object won't fit, then std::align returns null.

We may also want to create more than one object into that memory buffer, so we will need to know how much the pointer had been adjusted so that we can find out where we can create the next object. That is why space is a non-const reference argument. The function deducts the number of aligned bytes from space if the object fits.

Related