r/cpp • u/NekrozQliphort • Jan 10 '26
What I Learned About [[no_unique_address]] and Padding Reuse in C++
https://nekrozqliphort.github.io/posts/no-unique-address/
Hey everyone! It’s been a while since my last write-up. I recently spent some time looking into [[no_unique_address]], specifically whether it reliably saves space by reusing padding bytes. In a few cases, it didn’t behave quite as I expected, so I decided to dig a bit deeper.
This post is a short investigation into when padding reuse does and doesn't happen, with some concrete layout examples and ABI-level discussion.
Any feedback or corrections would be greatly appreciated!
52
Upvotes
17
u/matteding Jan 10 '26
Might want to add a blurb about
msvc::no_unique_address6
u/borzykot Jan 10 '26
Wow, good job. Once again, I'm convinced that one needs simplified model of C++ in his head, otherwise it just won't fit. All these nuances are just impenetrable and incomprehensible.
Me personally had this model regarding no_unique_address before I read this article:
mark (potentially) empty members with no_unique_adress and hope it will work, and another one:if you're using mixins (empty base classes) - better make sure that they are always have different types.And, tbh, I never though about no_unique_address as a mean for packing structures. So today I learned something about C++ again😅
3
u/LegitimateBottle4977 Jan 11 '26
Great blog post, thanks for writing it! I just shrunk a few objects. There are
static_asserts foelr 24B->16B and 80B->64B on MacOS. For some reason, objects were already smaller on Linux. Adding an empty base type didn't causestd::is_standard_layout_vto befalse, and it didn't seem enough on MacOS anyway because I already had base types for one class. Giving members different access specifiers did fix it. There's probably a better way than switching a field to be public, but this is great. https://github.com/LoopOptimization/Math/pull/60/files#diff-487f9384a0ef65146f224173d3189b58e04df6b79eed4d7fce30d3656a7572b4L7141
u/fdwr fdwr@github 🔍 Jan 13 '26 edited Jan 13 '26
Nekroz: Could tail packing work via inheritance rather than composition?
One aspect found in HLSL that I miss in C++ is constant buffer tail packing (mind you, it had other annoying packing rules, but that aspect was nice).