SlideShare a Scribd company logo
Smart->Pointers*
Smart Pointers 
Introduction 
RAII 
What are they ? 
Examples of Smart Pointers 
Benefits of Smart Pointers
Introduction 
In programming, the use of pointers are the main source of 
errors (or bugs) when developing code. 
The main problem found are the occurrences of memory 
leaks, this is due to the way pointers interact with memory, 
such as allocation and deallocation, which when 
performed inefficiently can cause the pointer to hang (or 
dangle, meaning that the pointer points to a previous 
removed object). 
The solution to this problem is the use of Smart Pointers.
RAII 
This is a programming idiom, In RAII, holding a 
resource is tied to object lifetime: resource 
allocation (acquisition) is done during object 
creation (specifically initialization), by the 
constructor, while resource deallocation (release) 
is done during object destruction, by the 
destructor. If objects are destructed properly, 
resource leaks do not occur.
Goal of RAII 
The main goal of this idiom is-> 
1] To ensure that resource acquisition occurs at the same 
time that the object is initialized, so that all resources for 
the object are created and made ready in one line of 
code. 
2] The resource is automatically freed when the object 
gets out of scope.
RAII 
Obtain Resource 
Use Resource 
Release Resource
Smart pointers 
 Smart pointers are crucial to the RAII or Resource Acquisition Is 
Initialialization programming idiom. 
 Smart pointers are class objects that behave like built-in pointers. 
 They also support pointer operations like dereferencing (operator *) 
and indirection (operator ->). 
To be smarter than regular pointers, smart pointers need to do things 
that regular pointers don't. What could these things be? Probably the 
most common bugs in C++ (and C) are related to pointers and 
memory management: dangling pointers, memory leaks, allocation 
failures and other joys. Having a smart pointer take care of these things 
can save a lot of aspirin..
Smart pointers 
1] std::auto_ptr 
2] std::unique_ptr [c++ 11] 
3] boost::shared_ptr 
4] std::shared [c++ 11] 
5] boost::scoped_ptr 
6] boost ::weak_ptr
It is common to write code such 
as.. 
void myFunction() 
{ 
myClass *p (new myClass()); 
p->Dosomething(); 
delete p; 
}
Example of smart pointers 
This code may work. But what if somewhere in the function body an 
exception gets thrown? Suddenly, the delete code never gets called! 
In this case a memory leak waiting to happen. 
However the use of a smart pointer will remove this threat due to the 
automatic clean up of the pointer because the pointer will be cleaned 
up whenever it gets out of scope, whether it was during the normal 
path of execution or during an exception. 
Auto_ptr: the simplest smart pointer to use. For situations when there 
are no special requirements.
auto_ptr 
 auto_ptr is a class template available in the 
C++ Standard Library (declared in the 
<memory> header file) that provides some 
basic RAII features for C++ raw pointers. 
 The auto_ptr template class describes an 
object that stores a pointer to a single 
allocated object of type Type* that ensures 
that the object to which it points gets 
destroyed automatically when control leaves a 
scope.
auto_ptr 
void myFunction() 
{ 
auto_ptr<myClass> *p (new myClass()); 
p->DoSomething(); 
//delete obj; /*memory allocated will 
automatically be freed*/ 
}
An Example of Smart Pointers 
void foo() 
{ 
MyClass* p(new 
MyClass); 
p->DoSomething(); 
delete p; 
} 
void foo() 
{ 
auto_ptr<MyClass> 
p(new MyClass); 
p->DoSomething(); 
}
auto_ptr 
The auto_ptr has semantics of strict ownership, meaning that the 
auto_ptr instance is the sole entity responsible for the object's lifetime. If 
an auto_ptr is copied, the source loses the reference. For example: 
MyClass* p(new MyClass); 
MyClass* q = p; 
delete p; 
p->DoSomething(); // Watch out! p is now dangling! 
p = NULL; // p is no longer dangling 
q->DoSomething(); // q is still dangling!
An Example of Smart Pointers 
For auto_ptr, this is solved by setting its pointer to NULL when it is copied: 
int main(int argc, char **argv) 
{ 
int *i = new int; 
auto_ptr<int> x(i); 
auto_ptr<int> y; 
y = x; 
cout << x.get() << endl; // Print NULL 
cout << y.get() << endl; // Print non-NULL address i
An Example of Smart Pointers 
This code will print a NULL address for the first 
auto_ptr object and some non-NULL address for 
the second, showing that the source object lost 
the reference during the assignment (=). The raw 
pointer i in the example should not be deleted, as 
it will be deleted by the auto_ptr that owns the 
reference. In fact, new int could be passed 
directly into x, eliminating the need for i.
#include <memory> // for std::auto_ptr 
#include <stdlib.h> // for EXIT_SUCCESS 
using namespace std; 
typedef struct { int a, b; } IntPair; 
int main(int argc, char **argv) { 
auto_ptr<int> x(new int(5)); 
// Return a pointer to the pointed-to object. 
int *ptr = x.get(); 
// Return a reference to the value of the pointed-to object. 
int val = *x; 
// Access a field or function of a pointed-to object. 
auto_ptr<IntPair> ip(new IntPair); 
ip->a = 100; 
// Reset the auto_ptr with a new heap-allocated object. 
x.reset(new int(1)); 
// Release responsibility for freeing the pointed-to object. 
ptr = x.release(); 
delete ptr; 
return EXIT_SUCCESS;
auto_ptr details… 
template <class T> class auto_ptr 
{ 
T* ptr; 
public: 
explicit auto_ptr(T* p = 0) : ptr(p) {} 
~auto_ptr() {delete ptr;} 
T& operator*() {return *ptr;} 
T* operator->() {return ptr;} 
};
auto_ptr details… 
template <class T> 
auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<T>& rhs) 
{ 
if (this != &rhs) 
{ 
delete ptr; 
ptr = rhs.ptr; 
rhs.ptr = NULL; 
} 
return *this; 
}
Problem with auto_ptr 
The C++ Standard says that an STL element must be "copy-constructible" and 
"assignable." In other words, an element must be able to be assigned or copied 
and the two elements are logically independent. std::auto_ptr does not fulfill this 
requirement. For example-void 
foo() { 
vector<auto_ptr< > > ivec; 
ivec.push_back(auto_ptr< >(new (5))); 
ivec.push_back(auto_ptr< >(new (6))); 
auto_ptr< > z = ivec[0]; 
}
Problem with auto_ptr 
To overcome this limitation, you should use 
the std::unique_ptr, std::shared_ptr or 
std::weak_ptr smart pointers or the boost 
equivalents if you don't have C++11.
shared_ptr 
 Shared pointer is a smart pointer (a C++ object wih 
overloaded operator*() and operator->()) 
 It keeps a pointer to an object and a pointer to a shared 
reference count. 
 Every time a copy of the smart pointer is made using the 
copy constructor, the reference count is incremented. 
 When a shared pointer is destroyed, the reference count 
for its object is decremented. 
 After counts goes to zero then managed object 
automatically get deleted.
int main(int argc, char **argv) { 
// x contains a pointer to an int and has reference count 1. 
boost::shared_ptr<int> x(new int(10)); 
{ 
// x and y now share the same pointer to an int, and they 
// share the reference count; the count is 2. 
boost::shared_ptr<int> y = x; 
std::cout << *y << std::endl; 
} 
// y fell out of scope and was destroyed. Therefore, the 
// reference count, which was previously seen by both x and y, 
// but now is seen only by x, is decremented to 1. 
return EXIT_SUCCESS; 
}
Finally, something that works! 
it is safe to store shared_ptrs in containers, since 
copy/assign maintain a shared reference count and 
pointer-
bool sortfunction(shared_ptr<int> x, shared_ptr<int> y) { 
return *x < *y; 
} 
bool printfunction(shared_ptr<int> x) { 
std::cout << *x << std::endl; 
} 
int main(int argc, char **argv) { 
vector<shared_ptr<int> > vec; 
vec.push_back(shared_ptr<int>(new int(9))); 
vec.push_back(shared_ptr<int>(new int(5))); 
vec.push_back(shared_ptr<int>(new int(7))); 
std::sort(vec.begin(), vec.end(), &sortfunction); 
std::for_each(vec.begin(), vec.end(), &printfunction); 
return EXIT_SUCCESS; 
}
How they work 
The process starts when the managed object is dynamically allocated, 
and the first shared_ptr (sp1) is created to point to it; the shared_ptr 
constructor creates a manager object (dynamically allocated). The 
manager object contains a pointer to the managed object; the 
overloaded member functions like shared_ptr::operator-> access the 
pointer in the manager object to get the actual pointer to the 
managed object.1 The manager object also contains two reference 
counts: The shared count counts the number of shared_ptrs pointing to 
the manager object, and the weak count counts the number of 
weak_ptrs pointing to the manager object. When sp1 and the 
manager object are first created, the shared count will be 1, and the 
weak count will be 0.
How they work… 
shared_ptr 
manager object 
managed object 
Pointer 
Shared count- 3 
Weak count- 2 
sp1 
sp2 
sp3 
wp1 wp2
How they work…. 
If another shared_ptr (sp2) is created by copy or assignment from sp1, 
then it also points to the same manager object, and the copy 
constructor or assignment operator increments the shared count to 
show that 2 shared_ptrs are now pointing to the managed object. 
Likewise, when a weak pointer is created by copy or assignment from 
a shared_ptr or another weak_ptr for this object, it points to the same 
manager object, and the weak count is incremented. The diagram 
shows the situation after three shared_ptrs and two weak_ptrs have 
been created to point to the same object.
Problem with shared_ptr 
If you used shared_ptr and have a cycle in the 
sharing graph, the reference count will never hit 
zero.
cycle of shared_ptr’s 
#include <boost/shared_ptr.hpp> 
boost::shared_ptr; 
A { 
shared_ptr<A> next; 
shared_ptr<A> prev; 
}; 
int main(int argc, char **argv) { 
shared_ptr<A> head( A()); 
head->next = shared_ptr<A>( A()); 
head->next->prev = head; 
} 
2 
0 
2 
1 
next 
prev 
0 
next 
prev 
head
breaking the cycle with weak_ptr 
A { 
shared_ptr<A> next; 
weak_ptr<A> prev; 
}; 
int main(int argc, char **argv) { 
shared_ptr<A> head(new A()); 
head->next = shared_ptr<A>(new A()); 
head->next->prev = head; 
} 
1 
0 
1 
1 
next 
prev 
0 
next 
prev 
head
#include <boost/shared_ptr.hpp> 
#include <boost/weak_ptr.hpp> 
#include <iostream> 
int main(int argc, char **argv) { 
boost::weak_ptr<int> w; 
{ 
boost::shared_ptr<int> x; 
{ 
boost::shared_ptr<int> y(new int(10)); 
w = y; 
x = w.lock(); 
std::cout << *x << std::endl; 
} 
std::cout << *x << std::endl; 
} 
boost::shared_ptr<int> a = w.lock(); 
std::cout << a << std::endl; 
return 0; 
}
use of make_shared to create an 
object 
If you need to create an object using a custom allocator, you can use 
make_shared. So, why use make_shared ? There are two main reasons: 
simplicity, and efficiency. 
 First, with make_shared the code is simpler. Write for clarity and 
correctness first. 
 Second, using make_shared is more efficient. 
The shared_ptr implementation has to maintain housekeeping 
information in a control block shared by all shared_ptrs 
and weak_ptrs referring to a given object. In particular, that 
housekeeping information has to include not just one but two 
reference counts:
use of make_shared to create an 
object 
 A “strong reference” count to track the number 
of shared_ptrs currently keeping the object alive. 
 A “weak reference” count to track the number 
of weak_ptrs currently observing the object. 
Example-sp1 
= shared_ptr<widget>{ new widget{} }; 
sp2 = sp1
use of make_shared to create an 
object
use of make_shared to create an 
object 
We’d like to avoid doing two separate allocations 
here. If you use make_shared to allocate the 
object and the shared_ptr all in one go, then the 
implementation can fold them together in a single 
allocation, as shown in Example-sp1 
= make_shared<widget>(); 
sp2 = sp1;
use of make_shared to create an 
object
use of make_shared to create an 
object 
 It reduces allocation overhead, including 
memory fragmentation. 
 It improves locality. The reference counts 
are frequently used with the object, and 
for small objects are likely to be on the 
same cache line, which improves cache 
performance.

More Related Content

What's hot

Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
ShriKant Vashishtha
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
sachindane
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Anil Bapat
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
Vishalini Mugunen
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
ppd1961
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
ThamizhselviKrishnam
 
Pass by value and pass by reference
Pass by value and pass by reference Pass by value and pass by reference
Pass by value and pass by reference
TurnToTech
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
Ankur Pandey
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
Ilio Catallo
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
P M Patil
 

What's hot (20)

Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Chap 6(decision making-looping)
Chap 6(decision making-looping)Chap 6(decision making-looping)
Chap 6(decision making-looping)
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Pass by value and pass by reference
Pass by value and pass by reference Pass by value and pass by reference
Pass by value and pass by reference
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
 

Similar to Smart pointers

C++ tutorial boost – 2013
C++ tutorial   boost – 2013C++ tutorial   boost – 2013
C++ tutorial boost – 2013
Ratsietsi Mokete
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
Jagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
lavparmar007
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
Ashirwad2
 
C questions
C questionsC questions
C questions
parm112
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
Akash Gawali
 
One Careful Owner
One Careful OwnerOne Careful Owner
One Careful Owner
Kevlin Henney
 
Smart Pointer in C++
Smart Pointer in C++Smart Pointer in C++
Smart Pointer in C++永泉 韩
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
HimanshuSharma997566
 
Data structures using C
Data structures using CData structures using C
Data structures using C
Pdr Patnaik
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02
Salman Qamar
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
sheibansari
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Selvaraj Seerangan
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
Gamindu Udayanga
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
Sabi995708
 
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
Steffen Wenz
 

Similar to Smart pointers (20)

C++ tutorial boost – 2013
C++ tutorial   boost – 2013C++ tutorial   boost – 2013
C++ tutorial boost – 2013
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
 
C questions
C questionsC questions
C questions
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
One Careful Owner
One Careful OwnerOne Careful Owner
One Careful Owner
 
Smart Pointer in C++
Smart Pointer in C++Smart Pointer in C++
Smart Pointer in C++
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
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
 

Recently uploaded

openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 

Recently uploaded (20)

openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 

Smart pointers

  • 2. Smart Pointers Introduction RAII What are they ? Examples of Smart Pointers Benefits of Smart Pointers
  • 3. Introduction In programming, the use of pointers are the main source of errors (or bugs) when developing code. The main problem found are the occurrences of memory leaks, this is due to the way pointers interact with memory, such as allocation and deallocation, which when performed inefficiently can cause the pointer to hang (or dangle, meaning that the pointer points to a previous removed object). The solution to this problem is the use of Smart Pointers.
  • 4. RAII This is a programming idiom, In RAII, holding a resource is tied to object lifetime: resource allocation (acquisition) is done during object creation (specifically initialization), by the constructor, while resource deallocation (release) is done during object destruction, by the destructor. If objects are destructed properly, resource leaks do not occur.
  • 5. Goal of RAII The main goal of this idiom is-> 1] To ensure that resource acquisition occurs at the same time that the object is initialized, so that all resources for the object are created and made ready in one line of code. 2] The resource is automatically freed when the object gets out of scope.
  • 6. RAII Obtain Resource Use Resource Release Resource
  • 7. Smart pointers  Smart pointers are crucial to the RAII or Resource Acquisition Is Initialialization programming idiom.  Smart pointers are class objects that behave like built-in pointers.  They also support pointer operations like dereferencing (operator *) and indirection (operator ->). To be smarter than regular pointers, smart pointers need to do things that regular pointers don't. What could these things be? Probably the most common bugs in C++ (and C) are related to pointers and memory management: dangling pointers, memory leaks, allocation failures and other joys. Having a smart pointer take care of these things can save a lot of aspirin..
  • 8. Smart pointers 1] std::auto_ptr 2] std::unique_ptr [c++ 11] 3] boost::shared_ptr 4] std::shared [c++ 11] 5] boost::scoped_ptr 6] boost ::weak_ptr
  • 9. It is common to write code such as.. void myFunction() { myClass *p (new myClass()); p->Dosomething(); delete p; }
  • 10. Example of smart pointers This code may work. But what if somewhere in the function body an exception gets thrown? Suddenly, the delete code never gets called! In this case a memory leak waiting to happen. However the use of a smart pointer will remove this threat due to the automatic clean up of the pointer because the pointer will be cleaned up whenever it gets out of scope, whether it was during the normal path of execution or during an exception. Auto_ptr: the simplest smart pointer to use. For situations when there are no special requirements.
  • 11. auto_ptr  auto_ptr is a class template available in the C++ Standard Library (declared in the <memory> header file) that provides some basic RAII features for C++ raw pointers.  The auto_ptr template class describes an object that stores a pointer to a single allocated object of type Type* that ensures that the object to which it points gets destroyed automatically when control leaves a scope.
  • 12. auto_ptr void myFunction() { auto_ptr<myClass> *p (new myClass()); p->DoSomething(); //delete obj; /*memory allocated will automatically be freed*/ }
  • 13. An Example of Smart Pointers void foo() { MyClass* p(new MyClass); p->DoSomething(); delete p; } void foo() { auto_ptr<MyClass> p(new MyClass); p->DoSomething(); }
  • 14. auto_ptr The auto_ptr has semantics of strict ownership, meaning that the auto_ptr instance is the sole entity responsible for the object's lifetime. If an auto_ptr is copied, the source loses the reference. For example: MyClass* p(new MyClass); MyClass* q = p; delete p; p->DoSomething(); // Watch out! p is now dangling! p = NULL; // p is no longer dangling q->DoSomething(); // q is still dangling!
  • 15. An Example of Smart Pointers For auto_ptr, this is solved by setting its pointer to NULL when it is copied: int main(int argc, char **argv) { int *i = new int; auto_ptr<int> x(i); auto_ptr<int> y; y = x; cout << x.get() << endl; // Print NULL cout << y.get() << endl; // Print non-NULL address i
  • 16. An Example of Smart Pointers This code will print a NULL address for the first auto_ptr object and some non-NULL address for the second, showing that the source object lost the reference during the assignment (=). The raw pointer i in the example should not be deleted, as it will be deleted by the auto_ptr that owns the reference. In fact, new int could be passed directly into x, eliminating the need for i.
  • 17. #include <memory> // for std::auto_ptr #include <stdlib.h> // for EXIT_SUCCESS using namespace std; typedef struct { int a, b; } IntPair; int main(int argc, char **argv) { auto_ptr<int> x(new int(5)); // Return a pointer to the pointed-to object. int *ptr = x.get(); // Return a reference to the value of the pointed-to object. int val = *x; // Access a field or function of a pointed-to object. auto_ptr<IntPair> ip(new IntPair); ip->a = 100; // Reset the auto_ptr with a new heap-allocated object. x.reset(new int(1)); // Release responsibility for freeing the pointed-to object. ptr = x.release(); delete ptr; return EXIT_SUCCESS;
  • 18. auto_ptr details… template <class T> class auto_ptr { T* ptr; public: explicit auto_ptr(T* p = 0) : ptr(p) {} ~auto_ptr() {delete ptr;} T& operator*() {return *ptr;} T* operator->() {return ptr;} };
  • 19. auto_ptr details… template <class T> auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<T>& rhs) { if (this != &rhs) { delete ptr; ptr = rhs.ptr; rhs.ptr = NULL; } return *this; }
  • 20. Problem with auto_ptr The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. std::auto_ptr does not fulfill this requirement. For example-void foo() { vector<auto_ptr< > > ivec; ivec.push_back(auto_ptr< >(new (5))); ivec.push_back(auto_ptr< >(new (6))); auto_ptr< > z = ivec[0]; }
  • 21. Problem with auto_ptr To overcome this limitation, you should use the std::unique_ptr, std::shared_ptr or std::weak_ptr smart pointers or the boost equivalents if you don't have C++11.
  • 22. shared_ptr  Shared pointer is a smart pointer (a C++ object wih overloaded operator*() and operator->())  It keeps a pointer to an object and a pointer to a shared reference count.  Every time a copy of the smart pointer is made using the copy constructor, the reference count is incremented.  When a shared pointer is destroyed, the reference count for its object is decremented.  After counts goes to zero then managed object automatically get deleted.
  • 23. int main(int argc, char **argv) { // x contains a pointer to an int and has reference count 1. boost::shared_ptr<int> x(new int(10)); { // x and y now share the same pointer to an int, and they // share the reference count; the count is 2. boost::shared_ptr<int> y = x; std::cout << *y << std::endl; } // y fell out of scope and was destroyed. Therefore, the // reference count, which was previously seen by both x and y, // but now is seen only by x, is decremented to 1. return EXIT_SUCCESS; }
  • 24. Finally, something that works! it is safe to store shared_ptrs in containers, since copy/assign maintain a shared reference count and pointer-
  • 25. bool sortfunction(shared_ptr<int> x, shared_ptr<int> y) { return *x < *y; } bool printfunction(shared_ptr<int> x) { std::cout << *x << std::endl; } int main(int argc, char **argv) { vector<shared_ptr<int> > vec; vec.push_back(shared_ptr<int>(new int(9))); vec.push_back(shared_ptr<int>(new int(5))); vec.push_back(shared_ptr<int>(new int(7))); std::sort(vec.begin(), vec.end(), &sortfunction); std::for_each(vec.begin(), vec.end(), &printfunction); return EXIT_SUCCESS; }
  • 26. How they work The process starts when the managed object is dynamically allocated, and the first shared_ptr (sp1) is created to point to it; the shared_ptr constructor creates a manager object (dynamically allocated). The manager object contains a pointer to the managed object; the overloaded member functions like shared_ptr::operator-> access the pointer in the manager object to get the actual pointer to the managed object.1 The manager object also contains two reference counts: The shared count counts the number of shared_ptrs pointing to the manager object, and the weak count counts the number of weak_ptrs pointing to the manager object. When sp1 and the manager object are first created, the shared count will be 1, and the weak count will be 0.
  • 27. How they work… shared_ptr manager object managed object Pointer Shared count- 3 Weak count- 2 sp1 sp2 sp3 wp1 wp2
  • 28. How they work…. If another shared_ptr (sp2) is created by copy or assignment from sp1, then it also points to the same manager object, and the copy constructor or assignment operator increments the shared count to show that 2 shared_ptrs are now pointing to the managed object. Likewise, when a weak pointer is created by copy or assignment from a shared_ptr or another weak_ptr for this object, it points to the same manager object, and the weak count is incremented. The diagram shows the situation after three shared_ptrs and two weak_ptrs have been created to point to the same object.
  • 29. Problem with shared_ptr If you used shared_ptr and have a cycle in the sharing graph, the reference count will never hit zero.
  • 30. cycle of shared_ptr’s #include <boost/shared_ptr.hpp> boost::shared_ptr; A { shared_ptr<A> next; shared_ptr<A> prev; }; int main(int argc, char **argv) { shared_ptr<A> head( A()); head->next = shared_ptr<A>( A()); head->next->prev = head; } 2 0 2 1 next prev 0 next prev head
  • 31. breaking the cycle with weak_ptr A { shared_ptr<A> next; weak_ptr<A> prev; }; int main(int argc, char **argv) { shared_ptr<A> head(new A()); head->next = shared_ptr<A>(new A()); head->next->prev = head; } 1 0 1 1 next prev 0 next prev head
  • 32. #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <iostream> int main(int argc, char **argv) { boost::weak_ptr<int> w; { boost::shared_ptr<int> x; { boost::shared_ptr<int> y(new int(10)); w = y; x = w.lock(); std::cout << *x << std::endl; } std::cout << *x << std::endl; } boost::shared_ptr<int> a = w.lock(); std::cout << a << std::endl; return 0; }
  • 33. use of make_shared to create an object If you need to create an object using a custom allocator, you can use make_shared. So, why use make_shared ? There are two main reasons: simplicity, and efficiency.  First, with make_shared the code is simpler. Write for clarity and correctness first.  Second, using make_shared is more efficient. The shared_ptr implementation has to maintain housekeeping information in a control block shared by all shared_ptrs and weak_ptrs referring to a given object. In particular, that housekeeping information has to include not just one but two reference counts:
  • 34. use of make_shared to create an object  A “strong reference” count to track the number of shared_ptrs currently keeping the object alive.  A “weak reference” count to track the number of weak_ptrs currently observing the object. Example-sp1 = shared_ptr<widget>{ new widget{} }; sp2 = sp1
  • 35. use of make_shared to create an object
  • 36. use of make_shared to create an object We’d like to avoid doing two separate allocations here. If you use make_shared to allocate the object and the shared_ptr all in one go, then the implementation can fold them together in a single allocation, as shown in Example-sp1 = make_shared<widget>(); sp2 = sp1;
  • 37. use of make_shared to create an object
  • 38. use of make_shared to create an object  It reduces allocation overhead, including memory fragmentation.  It improves locality. The reference counts are frequently used with the object, and for small objects are likely to be on the same cache line, which improves cache performance.