SlideShare a Scribd company logo
1 of 25
Download to read offline
Modern
C++ Memory
Management
By Alan Uthoff
Who is Alan
Uthoff?
• Founder and CEO of Swordpoint Studio, LLC
• Professional game developer 10+ years in C++
• Runs the C++ 17 Advanced Mentoring and Study
Group - Austin (CppMSG) and Austin Qt and QML
Developers Meetup
Modern Memory
Management
• Scoped base management 

• Clear intent and owner 

• Reduce errors and make errors detectable
C++ 98 Memory
Management
class myClass
{
public:
myClass()
{ m_dataPtr = new dataClass();}
virtual ~myClass()
{
if(m_dataPtr != NULL )
delete m_dataPtr;
}
private:
dataClass * m_dataPtr;
};
C++ 14 Memory
Management
// 98 way
class myClass
{
public:
myClass()
{ m_dataPtr = new
dataClass();}
virtual ~myClass()
{
if(m_dataPtr != NULL )
delete m_dataPtr;
}
private:
dataClass * m_dataPtr;
};
// 14 way
class myClass
{
public:
myClass(){ }
virtual ~myClass(){
}
private:
auto m_dataPtr =
std::make_unique<dataClass>()
;
};
std::unique_ptr
• #include <memory>

• Can not be copied 

• Can be moved 

• make_unique
std::unique_ptr
• std::unique_ptr 

• operator bool

• operator=

• operator->

• operator*

• operator[]

• get

• release
C++ 98 Factory
//With double pointers
void myClassFactory(myClass ** myDoublePtr)
{
*myDoublePtr = new myClass();
}
//return by pointer
myClass * myClassFactory()
{
return new myClass();
}
//Creates a lot of copies not very performant function
std::string myStringFactory()
{
//Creates two strings here
return "Hello World";
}
C++ 14 Factory
// 98 way
//With double pointers

void myClassFactory(myClass **
myDoublePtr)
{
*myDoublePtr = new myClass();
}
//return by pointer
myClass * myClassFactory()
{
return new myClass();
}
//Creates a lot of copies not very
performant function
std::string myStringFactory()
{
//Creates two strings here
return "Hello World";
}
// 14 way
std::unique_ptr<myClass> myClassFactory()
{
return make_unique<myClass>();
}
std::string myStringFactory()
{
//Returned by move
return "Hello World";
}


std::string myStringFactory()
{
std::string temp("Hello World");
//Returned by move or
//Copy Elision for prvalues in C++
//17 optional in C++ 11 and 14
return std::move(temp);
}
Move Semantics
• Adds new constructor and assignment operator 

• myClass(myClass && other) //move constructor

• myClass & operator=(myClass && other ) //move assignment
operator

• std::move cast lvalue to rvalue
class myClass{
public:
myClass() :
m_dataPtr(std::make_unique<dataClass>()) {}
virtual ~myClass(){}
myClass(myClass && other):
m_dataPtr(std::move(other.m_dataPtr)) {
other.m_dataPtr = nullptr;
}
myClass & operator=(myClass && other ) {
if(this != &other){
m_dataPtr = std::move(other.m_dataPtr);
other.m_dataPtr = nullptr; }
return *this;
}
private:
std::unique_ptr<dataClass> m_dataPtr = nullptr;
};
myClass myClassFactory()
{
myClass temp;
return std::move(temp);
}
int main()
{
myClass myObj = myClassFactory();
}
Copy Elision
• Constructs the object in place avoiding extra copies 

• T x = T(T(T()));// only one call to default constructor of T, to initialize 

• T f() { return T{}; }

• T x = f(); // only one call to default constructor of T, to initialize x

• T* p = new T(f()); // only one call to default constructor of T, to
initialize *p

• Guaranteed for prvalues in C++ 17 

• Optional in C++ 11 and 14
Examples taken from http://en.cppreference.com/w/cpp/language/copy_elision
std::shared_ptr
• #include <memory>

• make_shared

• Copy constructor or copy assignment of the shared_ptr
increments refcount 

• Decrements when the shard pointer instance is destroyed
std::shared_ptr
• std::shared_ptr

• use_count

• get

• operator=

• operator*

• operator->

• operator bool
std::shared_ptr example
void processData(std::shared_ptr<dataClass> p)
{
// thread-safe, even though the shared use_count is
incremented
std::shared_ptr<dataClass> lp = p;
lp->threadSafeProcessData();
}
auto p = std::make_shared<dataClass>();
std::thread t1(processData, p), t2(processData, p),
t3(processData, p);
p.reset(); // release ownership from main
t1.join(); t2.join(); t3.join();
std::cout << "All threads completed, the last one deleted
Derivedn";
Example taken http://en.cppreference.com/w/cpp/memory/shared_ptr
std::weak_ptr
• #include <memory>

• std::weak_ptr

• user_count 

• expired

• rest

• lock

• Does not increment the shared_ptr only the control block
std::weak_ptr example
auto sharedptr =
std::make_shared<int>(42);
std::weak_ptr<int> weakptr = sharedptr;
if (auto validSharedptr =
weakptr.lock())
{
//good ptr use validSharedptr
}else{
//memory is gone nullptr
}
Working with Legacy Code
void legacyFunction(const myClass * ptr )
{//do something …}
void legacyFunctionTakesOwnership(const myClass * ptr )
{//do something …}
myFactoryClass * legacyFactory( )
{return new myFactoryClass();}
void legacyFactoryDestroy(myFactoryClass * )
{delete myFactoryClass;}
int main()
{
auto uniquePtr = make_unique<myClass>();
legacyFunction(uniquePtr.get());
auto uniquePtr2 = make_unique<myClass>();
legacyFunctionTakesOwnership(uniquePtr2.release());
//can add a deleter as the second argument unique_ptr to have legacyFactoryDestroy
//called automaticity
std::unique_ptr<myFactoryClass> myFactoryPtr(legacyFactory());
legacyFactoryDestroy(myFactoryPtr.release());
}
std::any
• A type safe object that can hold any type of object

• Is a replacement for void pointers

• #include <any>

• std::any

• operator=

• emplace

• reset

• has_value

• type

• any_cast

• make_any

• bad_any_cast
std::any
bool processAny(std::any & valueToProcess)
{
if(!valueToProcess.has_value())
{
return false;
}
try{
if( valueToProcess.type() == typeid(A))
{
std::any_cast<A>(valueToProcess).process();
}
else if(valueToProcess.type() == typeid(B))
{
std::any_cast<B>(valueToProcess).process();
}
else
{
return false;
}
}
catch(const std::bad_any_cast)
{
//process bad any cast
return false;
}
return true;
}
std::optional
• May contain a value

• #include <optional>

• nullopt //type nullopt_t indicate that the optional is uninitialize
std::optional
• std::optional 

• operator->

• operator*

• operator bool / has_value

• value

• value_or

• reset

• emplace
std::optional
std::optional<unsigned int> myFactory(float value)
{
if(value < 0)
{
return std::nullopt;
}
return static_cast<unsigned int>(value);
}
int main()
{
std::optional<unsigned int> returnValue = myFactory(2.0f);
if(returnValue)
{
std::cout<<returnValue.value()<<std::endl;
}
else
{
std::cout<<"Failed to get value"<<std::endl;
}
}
http://alan.uthoff.us/presentations/ModernMemoryManagment
Questions?

More Related Content

What's hot

Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow controlSimon Su
 
Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Steffen Wenz
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itSergey Platonov
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereSergey Platonov
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
PyCon KR 2019 sprint - RustPython by example
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by exampleYunWon Jeong
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CSteffen Wenz
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIIAjit Nayak
 
Brief intro to clojure
Brief intro to clojureBrief intro to clojure
Brief intro to clojureRoy Rutto
 
Python opcodes
Python opcodesPython opcodes
Python opcodesalexgolec
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.lnikolaeva
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Sergey Platonov
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part IAjit Nayak
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt IIAjit Nayak
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in GeckoChih-Hsuan Kuo
 

What's hot (20)

Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow control
 
Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016
 
dplyr
dplyrdplyr
dplyr
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
PyCon KR 2019 sprint - RustPython by example
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by example
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt III
 
Dafunctor
DafunctorDafunctor
Dafunctor
 
Brief intro to clojure
Brief intro to clojureBrief intro to clojure
Brief intro to clojure
 
Python opcodes
Python opcodesPython opcodes
Python opcodes
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt II
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 

Similar to Modern c++ Memory Management

C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointerLei Yu
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer developmentAndrey Karpov
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak PROIDEA
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notesRajiv Gupta
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksBeginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksJinTaek Seo
 
Nodejs性能分析优化和分布式设计探讨
Nodejs性能分析优化和分布式设计探讨Nodejs性能分析优化和分布式设计探讨
Nodejs性能分析优化和分布式设计探讨flyinweb
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Dina Goldshtein
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerPlatonov Sergey
 
Simple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialSimple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialJin-Hwa Kim
 
4Developers 2018: Beyond c++17 (Mateusz Pusz)
4Developers 2018: Beyond c++17 (Mateusz Pusz)4Developers 2018: Beyond c++17 (Mateusz Pusz)
4Developers 2018: Beyond c++17 (Mateusz Pusz)PROIDEA
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Languagemspline
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 

Similar to Modern c++ Memory Management (20)

C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksBeginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
 
Nodejs性能分析优化和分布式设计探讨
Nodejs性能分析优化和分布式设计探讨Nodejs性能分析优化和分布式设计探讨
Nodejs性能分析优化和分布式设计探讨
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory Sanitizer
 
Lecture5
Lecture5Lecture5
Lecture5
 
Simple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialSimple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorial
 
4Developers 2018: Beyond c++17 (Mateusz Pusz)
4Developers 2018: Beyond c++17 (Mateusz Pusz)4Developers 2018: Beyond c++17 (Mateusz Pusz)
4Developers 2018: Beyond c++17 (Mateusz Pusz)
 
report
reportreport
report
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Modern c++
Modern c++Modern c++
Modern c++
 

Recently uploaded

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Recently uploaded (20)

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

Modern c++ Memory Management

  • 2. Who is Alan Uthoff? • Founder and CEO of Swordpoint Studio, LLC • Professional game developer 10+ years in C++ • Runs the C++ 17 Advanced Mentoring and Study Group - Austin (CppMSG) and Austin Qt and QML Developers Meetup
  • 3. Modern Memory Management • Scoped base management • Clear intent and owner • Reduce errors and make errors detectable
  • 4. C++ 98 Memory Management class myClass { public: myClass() { m_dataPtr = new dataClass();} virtual ~myClass() { if(m_dataPtr != NULL ) delete m_dataPtr; } private: dataClass * m_dataPtr; };
  • 5. C++ 14 Memory Management // 98 way class myClass { public: myClass() { m_dataPtr = new dataClass();} virtual ~myClass() { if(m_dataPtr != NULL ) delete m_dataPtr; } private: dataClass * m_dataPtr; }; // 14 way class myClass { public: myClass(){ } virtual ~myClass(){ } private: auto m_dataPtr = std::make_unique<dataClass>() ; };
  • 6. std::unique_ptr • #include <memory> • Can not be copied • Can be moved • make_unique
  • 7. std::unique_ptr • std::unique_ptr • operator bool • operator= • operator-> • operator* • operator[] • get • release
  • 8. C++ 98 Factory //With double pointers void myClassFactory(myClass ** myDoublePtr) { *myDoublePtr = new myClass(); } //return by pointer myClass * myClassFactory() { return new myClass(); } //Creates a lot of copies not very performant function std::string myStringFactory() { //Creates two strings here return "Hello World"; }
  • 9. C++ 14 Factory // 98 way //With double pointers void myClassFactory(myClass ** myDoublePtr) { *myDoublePtr = new myClass(); } //return by pointer myClass * myClassFactory() { return new myClass(); } //Creates a lot of copies not very performant function std::string myStringFactory() { //Creates two strings here return "Hello World"; } // 14 way std::unique_ptr<myClass> myClassFactory() { return make_unique<myClass>(); } std::string myStringFactory() { //Returned by move return "Hello World"; } 
 std::string myStringFactory() { std::string temp("Hello World"); //Returned by move or //Copy Elision for prvalues in C++ //17 optional in C++ 11 and 14 return std::move(temp); }
  • 10. Move Semantics • Adds new constructor and assignment operator • myClass(myClass && other) //move constructor • myClass & operator=(myClass && other ) //move assignment operator • std::move cast lvalue to rvalue
  • 11. class myClass{ public: myClass() : m_dataPtr(std::make_unique<dataClass>()) {} virtual ~myClass(){} myClass(myClass && other): m_dataPtr(std::move(other.m_dataPtr)) { other.m_dataPtr = nullptr; } myClass & operator=(myClass && other ) { if(this != &other){ m_dataPtr = std::move(other.m_dataPtr); other.m_dataPtr = nullptr; } return *this; } private: std::unique_ptr<dataClass> m_dataPtr = nullptr; };
  • 12. myClass myClassFactory() { myClass temp; return std::move(temp); } int main() { myClass myObj = myClassFactory(); }
  • 13. Copy Elision • Constructs the object in place avoiding extra copies • T x = T(T(T()));// only one call to default constructor of T, to initialize • T f() { return T{}; } • T x = f(); // only one call to default constructor of T, to initialize x • T* p = new T(f()); // only one call to default constructor of T, to initialize *p • Guaranteed for prvalues in C++ 17 • Optional in C++ 11 and 14 Examples taken from http://en.cppreference.com/w/cpp/language/copy_elision
  • 14. std::shared_ptr • #include <memory> • make_shared • Copy constructor or copy assignment of the shared_ptr increments refcount • Decrements when the shard pointer instance is destroyed
  • 15. std::shared_ptr • std::shared_ptr • use_count • get • operator= • operator* • operator-> • operator bool
  • 16. std::shared_ptr example void processData(std::shared_ptr<dataClass> p) { // thread-safe, even though the shared use_count is incremented std::shared_ptr<dataClass> lp = p; lp->threadSafeProcessData(); } auto p = std::make_shared<dataClass>(); std::thread t1(processData, p), t2(processData, p), t3(processData, p); p.reset(); // release ownership from main t1.join(); t2.join(); t3.join(); std::cout << "All threads completed, the last one deleted Derivedn"; Example taken http://en.cppreference.com/w/cpp/memory/shared_ptr
  • 17. std::weak_ptr • #include <memory> • std::weak_ptr • user_count • expired • rest • lock • Does not increment the shared_ptr only the control block
  • 18. std::weak_ptr example auto sharedptr = std::make_shared<int>(42); std::weak_ptr<int> weakptr = sharedptr; if (auto validSharedptr = weakptr.lock()) { //good ptr use validSharedptr }else{ //memory is gone nullptr }
  • 19. Working with Legacy Code void legacyFunction(const myClass * ptr ) {//do something …} void legacyFunctionTakesOwnership(const myClass * ptr ) {//do something …} myFactoryClass * legacyFactory( ) {return new myFactoryClass();} void legacyFactoryDestroy(myFactoryClass * ) {delete myFactoryClass;} int main() { auto uniquePtr = make_unique<myClass>(); legacyFunction(uniquePtr.get()); auto uniquePtr2 = make_unique<myClass>(); legacyFunctionTakesOwnership(uniquePtr2.release()); //can add a deleter as the second argument unique_ptr to have legacyFactoryDestroy //called automaticity std::unique_ptr<myFactoryClass> myFactoryPtr(legacyFactory()); legacyFactoryDestroy(myFactoryPtr.release()); }
  • 20. std::any • A type safe object that can hold any type of object • Is a replacement for void pointers • #include <any> • std::any • operator= • emplace • reset • has_value • type • any_cast • make_any • bad_any_cast
  • 21. std::any bool processAny(std::any & valueToProcess) { if(!valueToProcess.has_value()) { return false; } try{ if( valueToProcess.type() == typeid(A)) { std::any_cast<A>(valueToProcess).process(); } else if(valueToProcess.type() == typeid(B)) { std::any_cast<B>(valueToProcess).process(); } else { return false; } } catch(const std::bad_any_cast) { //process bad any cast return false; } return true; }
  • 22. std::optional • May contain a value • #include <optional> • nullopt //type nullopt_t indicate that the optional is uninitialize
  • 23. std::optional • std::optional • operator-> • operator* • operator bool / has_value • value • value_or • reset • emplace
  • 24. std::optional std::optional<unsigned int> myFactory(float value) { if(value < 0) { return std::nullopt; } return static_cast<unsigned int>(value); } int main() { std::optional<unsigned int> returnValue = myFactory(2.0f); if(returnValue) { std::cout<<returnValue.value()<<std::endl; } else { std::cout<<"Failed to get value"<<std::endl; } }