SlideShare a Scribd company logo
1 of 10
Download to read offline
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

What's hot

CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java scriptCodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java scriptCodiLime
 
HKG15-207: Advanced Toolchain Usage Part 3
HKG15-207: Advanced Toolchain Usage Part 3HKG15-207: Advanced Toolchain Usage Part 3
HKG15-207: Advanced Toolchain Usage Part 3Linaro
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - englishJen Yee Hong
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centrejatin batra
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Phil Calçado
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersJen Yee Hong
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil Witecki
 
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...Phil Calçado
 
JVM code reading -- C2
JVM code reading -- C2JVM code reading -- C2
JVM code reading -- C2ytoshima
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and deletePlatonov Sergey
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstractionSergey Platonov
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеSergey Platonov
 
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip CalçadoJustjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip CalçadoPaulo Silveira
 
A Slipshod Check of the Visual C++ 2013 Library (update 3)
A Slipshod Check of the Visual C++ 2013 Library (update 3)A Slipshod Check of the Visual C++ 2013 Library (update 3)
A Slipshod Check of the Visual C++ 2013 Library (update 3)Andrey Karpov
 
What has to be paid attention when reviewing code of the library you develop
What has to be paid attention when reviewing code of the library you developWhat has to be paid attention when reviewing code of the library you develop
What has to be paid attention when reviewing code of the library you developAndrey Karpov
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 

What's hot (20)

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

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

Overview of C++20 and a deeper look into modules
Overview of C++20 and a deeper look into modulesOverview of C++20 and a deeper look into modules
Overview of C++20 and a deeper look into modulesmmeisenzahl
 
Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Hitesh Kumar
 
Module wise format oops questions
Module wise format oops questionsModule wise format oops questions
Module wise format oops questionsSANTOSH RATH
 
CAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxCAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxSurajgroupsvideo
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notesRajiv Gupta
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14Matthieu Garrigues
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builderMaurizio Vitale
 
pyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdfpyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdfAsher Sterkin
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...Andrey Karpov
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
Objective c beginner's guide
Objective c beginner's guideObjective c beginner's guide
Objective c beginner's guideTiago Faller
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++Mihai Todor
 
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMINGFINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMINGAmira Dolce Farhana
 
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderA Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderAndrey Karpov
 
Behavior driven oop
Behavior driven oopBehavior driven oop
Behavior driven oopPiyush Verma
 
C++ Interface Versioning
C++ Interface VersioningC++ Interface Versioning
C++ Interface VersioningSkills Matter
 
Two C++ Tools: Compiler Explorer and Cpp Insights
Two C++ Tools: Compiler Explorer and Cpp InsightsTwo C++ Tools: Compiler Explorer and Cpp Insights
Two C++ Tools: Compiler Explorer and Cpp InsightsAlison Chaiken
 

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

Overview of C++20 and a deeper look into modules
Overview of C++20 and a deeper look into modulesOverview of C++20 and a deeper look into modules
Overview of C++20 and a deeper look into modules
 
Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++
 
Module wise format oops questions
Module wise format oops questionsModule wise format oops questions
Module wise format oops questions
 
CAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxCAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptx
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
L6
L6L6
L6
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
 
pyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdfpyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdf
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
Objective c beginner's guide
Objective c beginner's guideObjective c beginner's guide
Objective c beginner's guide
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMINGFINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
 
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderA Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
 
Behavior driven oop
Behavior driven oopBehavior driven oop
Behavior driven oop
 
C++ Interface Versioning
C++ Interface VersioningC++ Interface Versioning
C++ Interface Versioning
 
Two C++ Tools: Compiler Explorer and Cpp Insights
Two C++ Tools: Compiler Explorer and Cpp InsightsTwo C++ Tools: Compiler Explorer and Cpp Insights
Two C++ Tools: Compiler Explorer and Cpp Insights
 
Securité des container
Securité des containerSecurité des container
Securité des container
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

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]]