r/cpp • u/kris-jusiak https://github.com/kris-jusiak • Jun 29 '23
[C++20] [[no_unique_address]] for 1 byte message views
https://twitter.com/krisjusiak/status/167435195113841459214
u/yuri-kilochek Jun 29 '23
How is this better than declaring a regular struct with regular fields, then overlaying it onto the byte buffer?
-8
u/kris-jusiak https://github.com/kris-jusiak Jun 29 '23
the size of the struct will be 1 (the minimal size required by C++ standard) instead of the sizeof(struct with fields) >=1 which may lead to better perf and better memory utilization; the use case is usually when dealing with data from the wire (which is packed) and then passed around with message types
17
u/ioctl79 Jun 29 '23
I am struggling to see how lying to the compiler saves any memory. Yes, your struct is only one byte, but it also doesnât contain any actual data, and it doesnât store a reference to any actual data, so it is using one byte to store nothing of value. Maybe come up with a concrete, practical example of how to use this that demonstrates the utility?
5
u/KuntaStillSingle Jun 29 '23
Do you have an example where it saves memory without overflowing? Your op only works because you are casting a the full sized object to a reference to your 'mini' object, so when you access the underlying fields they don't overstep the bounds of the actual underlying object, which is larger than 1 byte. If you try to use it to save space, like copy to your one byte object from that reference, you get overflow: https://godbolt.org/z/fT16TM5z7
15
u/trailingunderscore_ Jun 29 '23
Another twitter drive-by by kris, that again leaves everyone wondering "why?". These posts of his are bordering on spam.
15
u/sphere991 Jun 29 '23
My favorite part of this is:
[[nodiscard]] constexpr operator const T&() const noexcept { return *std::launder(std::bit_cast<const T*>(std::bit_cast<const char*>(this) + Offset)); }Both
bit_casts here are just reinterpreting one pointer to another, there's no reason to usebit_casthere at all - and none of this can beconstexpranyway. Thelaunderalso is pointless, we're not replacing objects anywhere here.So this is just a really long way of writing:
[[nodiscard]] operator const T&() const noexcept { return *(const T*)((const char*)this + Offset); }Your choice of parentheses may vary, some people would prefer to write out
reinterpret_castor introduce a local variable for the offset pointer.Just kidding, my actual favorite part is:
template <class T> [[nodiscard]] constexpr const T& buffer_cast(const void* msg) noexcept { return *(::new (const_cast<void*>(msg)) const T); }This is
constexprwhen it cannot, be, takes aconst void*when it actually needs to take avoid*... to construct a new object that it shouldn't be constructing.Which is just wrong, this really should be:
template <class T> [[nodiscard]] const T& buffer_cast(const void* msg) noexcept { return *(const T*)msg; }Either way, the whole thing is like: well, we could just write a normal type declaration and just access members directly:
struct [[gnu::packed]] trade { int32_t price; uint32_t size; side side; };Or we could manually calculate offsets and use a more verbose syntax for everything, that in some cases calls for explicit casts - since you need the conversion to happen so
autowon't work.Tough call!
3
u/trailingunderscore_ Jun 29 '23
The placement new would also end the lifetime of the object he is "casting" from, and make any further access UB.
4
u/oleksandrkvl Jun 30 '23
u/kris-jusiak your twitter page is not available for unregistered users so it's not possible to see what this thread is about
5
1
u/feverzsj Jun 29 '23
butt why?
-9
u/kris-jusiak https://github.com/kris-jusiak Jun 29 '23
By applying the [[no_unique_address]] attribute to the prices field, it indicates to the compiler that this field doesn't affect the object's unique identification. Consequently, the compiler can eliminate the storage for the prices field when calculating the size of the order struct. This optimization reduces the overall size of the order struct and potentially improves memory efficiency, so using the [[no_unique_address]] attribute in the provided code allows the compiler to optimize the memory layout and size of structures by removing members that don't contribute to the object's unique identification. This can lead to reduced memory consumption and potentially improved performance.
2
u/SirClueless Jun 30 '23
How does this accomplish anything that just reinterpret_cast of the bytes of the message to a trivially-constructible struct does not?
trade&takes exactly the same number of bytes (1) to pass around whether the struct is one byte or 50.
1
Jun 29 '23
I donât get it. Why not just use a pointer to the struct? Besides, how is it â1 byteâ, if one is using a reference (which is a pointer)?
2
u/thisismyfavoritename Jun 29 '23 edited Jun 29 '23
i think the struct has no fields in the eyes of the compiler, 1 is the minimal size to distinguish structs.
Not sure where you see the ref data member.
I had the same question as you regarding the first point, and looking at this further, i think the optimization is that the view is one byte vs 16 (say if you have a ptr to the start of the buffer and a size) or vs 8 if youre passing a ptr or ref to the object itself
6
Jun 29 '23
The one byte struct size does not matter since never actually exists as a value (you never allocate it). What they do is cast an existing struct as a reference to one of these one-byte structs. E.g. here
const auto& msg = buffer_cast<::trade>(std::addressof(trade));Note how the variable
msgis a reference (pointer). You need a pointer-sized block of memory to store it, not just one byte.In other words, this is the same as using a
void*pointer to a struct and grabbing pointers to members viaoffsetof(). Definitely a cool party trick and shows in-depth knowledge of C++ idiosyncrasies, but I don't see any practical utility. For all intends and purposes this is just an extremely awkward way of expressing references.1
u/thisismyfavoritename Jun 29 '23
yes i agree with your assessment, it feels like it would make a difference if you could use value semantics with the view but i dont think it would work here. I asked the OP in another comment
1
1
18
u/JessyDL graphics engineer/games industry Jun 29 '23
It would be nice if a little bit of motivation could be given as to why you'd basically want an object to lie about its size? Are you trying to sidestep cost for allocating the object, or constructing it? Or is this a "wow, neat, but never use this" (I'd lean this is the point of the example, but would be great to hear from you).