SlideShare una empresa de Scribd logo
1 de 38
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.

Más contenido relacionado

La actualidad más candente

Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++
Deepak Singh
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
kapil078
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 
Python decorators
Python decoratorsPython decorators
Python decorators
Alex Su
 

La actualidad más candente (20)

Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
STL in C++
STL in C++STL in C++
STL in C++
 
This pointer
This pointerThis pointer
This pointer
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Storage class
Storage classStorage class
Storage class
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 

Similar a Smart pointers

CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
Edward Chen
 
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
 

Similar a 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++
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Último (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
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
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

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.