Quick summary ↬ [[no_unique_address]] is a C++ 20 feature that helps in saving memory while declaring an empty struct or class and creating object for it in some other place.
Beautiful code #3
|
|
Beautiful code #3 Explanation
The above C++ code snippet is very simple but very beautiful one. This code snippet is useful while designing a library that could be installed and used in varieties of hardwares. We check whether a feature is available in the version of C++ installed and then we apply it. If it is not available the macro won’t pass the command in the codebase where it is called.
defined(__has_cpp_attribute) && __has_cpp_attribute(no_unique_address)
- This checks whether __has_cpp_attribute
is defined and then uses it to check whether the standard library installed in the system where the library is running has a particular feature. If [[no_unique_address]]
code is supported then the macro applies it in all the code where the macro is called.
[[no_unique_address]]
is a C++ 20 feature that is used infront of a struct
or class
which is empty. If used we could save 1 byte whenever an object is created for another class that instantiate the object for the empty struct
or class
. Not allocating memory for no reason is much needed functionality to develop a well optimized library.
In the above example Sentinel
is declared with [[no_unique_address]]
.
You will also like — More Articles
https://fluentprogrammer.com/beautiful-code-1-using-define-templates-r-value-reference/ https://fluentprogrammer.com/beautiful-code-2-enable_if_t-template-inside-a-template/ https://fluentprogrammer.com/beautiful-code-4-any_of-none_of-all_of/ https://fluentprogrammer.com/beautiful-code-5-for_each-optional/ https://fluentprogrammer.com/beautiful-code-6-copy_if-remove_copy_if-copy-back_inserter/