C++ Logo

std-proposals

Advanced search

Re: [std-proposals] [[packed]] std::unaligned

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sat, 9 Dec 2023 17:17:31 +0000
On Saturday, December 9, 2023, Thiago Macieira wrote:

> I think you're getting the cart ahead of the oxen.



Thinking back on all the little and big programs I've written in C++ since
around about 2002, I can think of only two use cases for having unaligned
data in memory.

The first is when I wrote a network analysis program and read packets in
from the network card, and I had a 'packed struct' to represent all of the
packet headers e.g. the IP header, the TCP header. Looking back now though,
that might all have been unnecessary if the packet headers were designed to
not need padding (and they probably all were), but anyway ya get the idea
here: reading the fields of a header from a file.

The second use case is where you go extreme with conserving memory. So
let's say on a microcontroller you have:

    struct TokenInfo {
        long unsigned a;
        char b;
        long unsigned c;
        char d;
    };

and you want to store a load of these in the EEPROM, and so you don't want
to waste space with padding. Now of course probably the first thing you'll
say to me is to change that to:

    struct TokenInfo {
        long unsigned a;
        long unsigned c;
        char b;
        char d;
    };

but maybe there's a reason why you can't re-order the members. But even if
you do re-order the members, you're still left with either 2 or 6 bytes of
tail padding (i.e. sizeof(T) == (__datasizeof(T) + sizeof(long unsigned) -
2)).

In both of these use cases, I'd much prefer if we could do the following:

    struct TokenInfo {
        long unsigned a;
        char b;
        long unsigned c;
        char d;
    };

    typedef struct TokenInfo [[packed]] TicketInfo;

So now 'TicketInfo' is a packed form of the 'TokenInfo' struct. I'd much
prefer this than having a new type called std::unaligned, but I just
entertained the idea of std::aligned here for no other reason than to
lubricate the conversation a little. It doesn't hurt to lean a little in
another person's direction before leaning back to where you were.

Received on 2023-12-09 17:17:33