SlideShare a Scribd company logo
EMPTY BASE CLASS OPTIMISATION,
[[NO_UNIQUE_ADDRESS]]
And Other C++20 Attributes…
Bartłomiej Filipek, bfilipek.com21st July 2020
About me
 See my coding blog at: www.bfilipek.com
 Slowly moving to cppstories.com
 ~13y coding experience
 Microsoft MVP, since 2018
 C++ ISO Member
 @Xara.com
 Mostly text related features for advanced
document editors
 Somehow addicted to C++ ☺
Xara Cloud DemoC++17 In Detail
The plan
 Unique_ptr and a custom deleter
 Digging into the STL implementation
 Empty Base Class Optimisation
 [[no_unique_address]]
 Other C++20 Attributes and Features
Custom deleter for unique_ptr
 Background, the article from 2016:
 https://www.bfilipek.com/2016/04/custom-deleters-for-c-smart-
pointers.html#custom-deleter-for-uniqueptr
 Why unique_ptr is just 8 bytes (one pointer) with default deleters? Or
stateless deleters?
 The working example with a custom deleter:
 http://coliru.stacked-crooked.com/a/e2638649daffd406
Digging into the STL implementation
 Let’s try to understand the internal implementation of unique_ptr
 We can go to:
 https://github.com/microsoft/STL
 https://github.com/microsoft/STL/blob/master/stl/inc/memory#L2435
 Unique_ptr seems to hold the pointer and the deleter in something
called compressed pair
 It has two specialisation: the first one if both types are non empty and the
second one if the first type is empty
◼ In that case it just declares one member field and derive from the empty type
◼ By inheritance we get access to all of the type member functions
Empty Base Class Optimisation
 When a class is empty it costs at least 1 byte on stack, but if you inherit
from such a class then in costs you nothing
 https://en.cppreference.com/w/cpp/language/ebo
 See an example:
 http://coliru.stacked-crooked.com/a/affe60d81ac52163
 Some example:
 https://github.com/microsoft/STL/blob/master/stl/inc/xmemory#L1319
 GCC tuple: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-
v3/include/bits/unique_ptr.h#L201
[[no_unique_address]]
 Let’s rewrite the compressed pair into something really simple thanks
to the new attribute from C++20
 http://coliru.stacked-crooked.com/a/7ccae3a3168e73b9
Attributes in C++17
[[noreturn]] indicates that the function does not return
[[carries_dependency]]
indicates that dependency chain in release-consume
std::memory_order propagates in and out of the function
[[deprecated]]
[[deprecated("reason")]]
indicates that the use of the name or entity declared with this
attribute is allowed, but discouraged for some reason
[[fallthrough]]
indicates that the fall through from the previous case label is
intentional and should not be diagnosed by a compiler that warns
on fall-through
[[nodiscard]]
encourages the compiler to issue a warning if the return value is
discarded
[[maybe_unused]] suppresses compiler warnings on unused entities, if any
https://www.bfilipek.com/2017/07/cpp17-in-details-attributes.html
https://www.bfilipek.com/2017/11/nodiscard.html
Attributes in C++20
[[nodiscard("reason")]]
encourages the compiler to issue a warning if the
return value is discarded
[[likely]]
[[unlikely]]
indicates that the compiler should optimize for the
case where a path of execution through a statement
is more or less likely than any other path of execution
[[no_unique_address]]
indicates that a non-static data member need not
have an address distinct from all other non-static
data members of its class
• Apply [[nodiscard]] to the standard library - P0600
• [[nodiscard]] for constructors - P1771
Summary
 Empty Base Class Optimisation relies on the fact that if you inherit
from a empty class then you don’t need more memory, but you get
access to member functions.
 The technique is however a bit complicated
 Thanks to the new C++20 attribute – [[no_unique_address]] the code can
be much simpler
 Since C++11 the Standard has been taking vendor specific annotation
syntax into a common form of [[attrib_name]].
 C++20 adds new attributes: [[no_unique_address]], [[likely]] and
[[unlikely]]

More Related Content

PPTX
Let's talks about string operations in C++17
PPTX
Vocabulary Types in C++17
PPTX
C++17 std::filesystem - Overview
PDF
C++20 the small things - Timur Doumler
PPTX
Hacking Go Compiler Internals / GoCon 2014 Autumn
PDF
Checking the Open-Source Multi Theft Auto Game
PDF
Writing good std::future<c++>
PDF
Антон Бикинеев, Writing good std::future< C++ >
Let's talks about string operations in C++17
Vocabulary Types in C++17
C++17 std::filesystem - Overview
C++20 the small things - Timur Doumler
Hacking Go Compiler Internals / GoCon 2014 Autumn
Checking the Open-Source Multi Theft Auto Game
Writing good std::future<c++>
Антон Бикинеев, Writing good std::future< C++ >

What's hot (19)

PDF
HKG15-207: Advanced Toolchain Usage Part 3
PDF
2018 cosup-delete unused python code safely - english
PPTX
Best Bugs from Games: Fellow Programmers' Mistakes
PPTX
C Programming Training in Ambala ! Batra Computer Centre
ZIP
Lisp Macros in 20 Minutes (Featuring Clojure)
PDF
Basic c++ 11/14 for python programmers
PDF
Kamil witecki asynchronous, yet readable, code
PDF
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
PDF
JVM code reading -- C2
PPTX
C++ Code as Seen by a Hypercritical Reviewer
PDF
С++ without new and delete
ODP
OpenGurukul : Language : C++ Programming
PPTX
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
PPTX
Дмитрий Нестерук, Паттерны проектирования в XXI веке
PDF
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
PPTX
C++ Core Guidelines
PDF
A Slipshod Check of the Visual C++ 2013 Library (update 3)
PPTX
What has to be paid attention when reviewing code of the library you develop
PPTX
How to Adopt Modern C++17 into Your C++ Code
HKG15-207: Advanced Toolchain Usage Part 3
2018 cosup-delete unused python code safely - english
Best Bugs from Games: Fellow Programmers' Mistakes
C Programming Training in Ambala ! Batra Computer Centre
Lisp Macros in 20 Minutes (Featuring Clojure)
Basic c++ 11/14 for python programmers
Kamil witecki asynchronous, yet readable, code
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
JVM code reading -- C2
C++ Code as Seen by a Hypercritical Reviewer
С++ without new and delete
OpenGurukul : Language : C++ Programming
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
C++ Core Guidelines
A Slipshod Check of the Visual C++ 2013 Library (update 3)
What has to be paid attention when reviewing code of the library you develop
How to Adopt Modern C++17 into Your C++ Code
Ad

Similar to Empty Base Class Optimisation, [[no_unique_address]] and other C++20 Attributes (20)

PDF
Smart Pointers in C++
PDF
smart pointers are unique concept to avoid memory leakage
PPTX
Useful C++ Features You Should be Using
PDF
C++11 smart pointer
PPT
C++ Interview Questions
PPTX
Smart pointers
PPTX
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
PPTX
PDF
Memory Management C++ (Peeling operator new() and delete())
PPTX
asic computer is an electronic device that can receive, store, process, and o...
PPT
Pointer
PPTX
12. MODULE 1.pptx
PPT
OOP in C++
PPTX
C++ Introduction brown bag
PPTX
Oop concept in c++ by MUhammed Thanveer Melayi
PDF
Software Design: Impact of Memory Usage (Copying, Cloning and Aliases)
PPTX
Lesson one 1 OOAD study/ref material.pptx
PPTX
PDF
CS225_Prelecture_Notes 2nd
Smart Pointers in C++
smart pointers are unique concept to avoid memory leakage
Useful C++ Features You Should be Using
C++11 smart pointer
C++ Interview Questions
Smart pointers
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
Memory Management C++ (Peeling operator new() and delete())
asic computer is an electronic device that can receive, store, process, and o...
Pointer
12. MODULE 1.pptx
OOP in C++
C++ Introduction brown bag
Oop concept in c++ by MUhammed Thanveer Melayi
Software Design: Impact of Memory Usage (Copying, Cloning and Aliases)
Lesson one 1 OOAD study/ref material.pptx
CS225_Prelecture_Notes 2nd
Ad

Recently uploaded (20)

PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Encapsulation theory and applications.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Understanding_Digital_Forensics_Presentation.pptx
cuic standard and advanced reporting.pdf
Spectral efficient network and resource selection model in 5G networks
Network Security Unit 5.pdf for BCA BBA.
Digital-Transformation-Roadmap-for-Companies.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
The AUB Centre for AI in Media Proposal.docx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Approach and Philosophy of On baking technology
Per capita expenditure prediction using model stacking based on satellite ima...
“AI and Expert System Decision Support & Business Intelligence Systems”
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
Encapsulation theory and applications.pdf
MYSQL Presentation for SQL database connectivity
Build a system with the filesystem maintained by OSTree @ COSCUP 2025

Empty Base Class Optimisation, [[no_unique_address]] and other C++20 Attributes

  • 1. EMPTY BASE CLASS OPTIMISATION, [[NO_UNIQUE_ADDRESS]] And Other C++20 Attributes… Bartłomiej Filipek, bfilipek.com21st July 2020
  • 2. About me  See my coding blog at: www.bfilipek.com  Slowly moving to cppstories.com  ~13y coding experience  Microsoft MVP, since 2018  C++ ISO Member  @Xara.com  Mostly text related features for advanced document editors  Somehow addicted to C++ ☺ Xara Cloud DemoC++17 In Detail
  • 3. The plan  Unique_ptr and a custom deleter  Digging into the STL implementation  Empty Base Class Optimisation  [[no_unique_address]]  Other C++20 Attributes and Features
  • 4. Custom deleter for unique_ptr  Background, the article from 2016:  https://www.bfilipek.com/2016/04/custom-deleters-for-c-smart- pointers.html#custom-deleter-for-uniqueptr  Why unique_ptr is just 8 bytes (one pointer) with default deleters? Or stateless deleters?  The working example with a custom deleter:  http://coliru.stacked-crooked.com/a/e2638649daffd406
  • 5. Digging into the STL implementation  Let’s try to understand the internal implementation of unique_ptr  We can go to:  https://github.com/microsoft/STL  https://github.com/microsoft/STL/blob/master/stl/inc/memory#L2435  Unique_ptr seems to hold the pointer and the deleter in something called compressed pair  It has two specialisation: the first one if both types are non empty and the second one if the first type is empty ◼ In that case it just declares one member field and derive from the empty type ◼ By inheritance we get access to all of the type member functions
  • 6. Empty Base Class Optimisation  When a class is empty it costs at least 1 byte on stack, but if you inherit from such a class then in costs you nothing  https://en.cppreference.com/w/cpp/language/ebo  See an example:  http://coliru.stacked-crooked.com/a/affe60d81ac52163  Some example:  https://github.com/microsoft/STL/blob/master/stl/inc/xmemory#L1319  GCC tuple: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B- v3/include/bits/unique_ptr.h#L201
  • 7. [[no_unique_address]]  Let’s rewrite the compressed pair into something really simple thanks to the new attribute from C++20  http://coliru.stacked-crooked.com/a/7ccae3a3168e73b9
  • 8. Attributes in C++17 [[noreturn]] indicates that the function does not return [[carries_dependency]] indicates that dependency chain in release-consume std::memory_order propagates in and out of the function [[deprecated]] [[deprecated("reason")]] indicates that the use of the name or entity declared with this attribute is allowed, but discouraged for some reason [[fallthrough]] indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fall-through [[nodiscard]] encourages the compiler to issue a warning if the return value is discarded [[maybe_unused]] suppresses compiler warnings on unused entities, if any https://www.bfilipek.com/2017/07/cpp17-in-details-attributes.html https://www.bfilipek.com/2017/11/nodiscard.html
  • 9. Attributes in C++20 [[nodiscard("reason")]] encourages the compiler to issue a warning if the return value is discarded [[likely]] [[unlikely]] indicates that the compiler should optimize for the case where a path of execution through a statement is more or less likely than any other path of execution [[no_unique_address]] indicates that a non-static data member need not have an address distinct from all other non-static data members of its class • Apply [[nodiscard]] to the standard library - P0600 • [[nodiscard]] for constructors - P1771
  • 10. Summary  Empty Base Class Optimisation relies on the fact that if you inherit from a empty class then you don’t need more memory, but you get access to member functions.  The technique is however a bit complicated  Thanks to the new C++20 attribute – [[no_unique_address]] the code can be much simpler  Since C++11 the Standard has been taking vendor specific annotation syntax into a common form of [[attrib_name]].  C++20 adds new attributes: [[no_unique_address]], [[likely]] and [[unlikely]]