SlideShare une entreprise Scribd logo
1  sur  35
05 | Pointers and RAII
Kate Gregory | Gregory Consulting
James McNellis | Senior Engineer, Visual C++
Module Overview
1. Pointers
2. Dynamic Allocation
3. Exceptions
4. Copying, Assignment, and Destruction
5. Resource Acquisition is Initialization (RAII)
6. Smart Pointers
Module Overview
1. Pointers
2. Dynamic Allocation
3. Exceptions
4. Copying, Assignment, and Destruction
5. Resource Acquisition is Initialization (RAII)
6. Smart Pointers
Lesson 1: Pointers
void f()
{
int x{1};
int y{2};
}

…

x

y

…
Lesson 1: Pointers
void f()
{
int x{1};
int y{2};
}
&x

…

&y
x

y

…
Lesson 1: Pointers
void f()
{
int x{1};
int y{2};
int* pointer_to_x{&x};
int* pointer_to_y{&y};

}
Lesson 1: Pointers
void f()
{
int x{1};
int* pointer_to_x{&x};
int y{*pointer_to_x};

}
Lesson 1: Pointers
void f()
{
int x{1};
int* pointer_to_x{&x};
*pointer_to_x = 2;

}
Lesson 1: Pointers
void f()
{
int x{1};
int y{2};
int* p{&x};
p = &y;

}
Lesson 1: Pointers
void f()
{
int p{nullptr};
}
DEMO
Pointers
Module Overview
1. Pointers
2. Dynamic Allocation
3. Exceptions
4. Copying, Assignment, and Destruction
5. Resource Acquisition is Initialization (RAII)
6. Smart Pointers
Lesson 2: Dynamic Allocation
• Objects have scope, and go away when execution reaches
the end of that scope
void f()
{
NamedRectangle fred_rectangle{ "Fred", 3, 4 };

// . . .
}

• What if other code needed that object still?
The Free Store
• Separate area of memory
• Objects created there stick around until deliberately cleaned
up
• To create one, use new – returns a pointer
• To clean up, use delete
The Free Store
void f()
{
int* p{new int{1}};
*p = 2;
delete p;
}
DEMO
Pointers
Module Overview
1. Pointers
2. Dynamic Allocation
3. Exceptions
4. Copying, Assignment, and Destruction
5. Resource Acquisition is Initialization (RAII)
6. Smart Pointers
Exceptions
• Sometimes what you want can’t be done
– That file doesn’t exist any more
– You don’t have permission to do that to the system

• Checking in advance is best, but not always possible
• Code that calls a function doesn’t need to check return value

• C++ provides a non ignorable signal that something awful
has happened
• Will return from any nested level of function calls to a place
that can handle the error
Exception syntax
try
{
// anything, including function calls
}
catch (const std::exception& e)
{
std::cout << "Exception caught: " << e.what();

}
DEMO
Exceptions
Module Overview
1. Pointers
2. Dynamic Allocation
3. Exceptions
4. Copying, Assignment, and Destruction
5. Resource Acquisition is Initialization (RAII)
6. Smart Pointers
Copying, Assignment, and Destruction
void f()
{
int x{1};
int y{x}; // Copying
y = x;
}

// Assignment
Copying, Assignment, and Destruction
void f()
{
Rectangle x{3, 4};
Rectangle y{x}; // Copying
y = x;
}

// Assignment
Copying, Assignment, and Destruction
• Copying a class-type object invokes a special constructor
– Called the copy constructor
– Rectangle(Rectangle const&);
– If you don’t define one, the compiler provides one by default

• The default behaviour is to copy each base and data
member
Copying, Assignment, and Destruction
• Copying a class-type object invokes a special constructor
– Called the copy constructor
– Rectangle(Rectangle const&);
– If you don’t define one, the compiler provides one by default

• The default behaviour is to copy each base and data
member
Rectangle(Rectangle const& other)

: _width{other._width}, _height{other._height}
Copying, Assignment, and Destruction
• Assigning to a class-type object invokes a special operator
– Called the assignment operator
– Rectangle& operator=(Rectangle const&);
– If you don’t define one, the compiler provides one by default

• The default behaviour is to assign each base and data
member
Copying, Assignment, and Destruction
• Assigning to a class-type object invokes a special operator
– Called the assignment operator
– Rectangle& operator=(Rectangle const&);
– If you don’t define one, the compiler provides one by default

• The default behaviour is to assign each base and data member
Rectangle& operator=(Rectangle const& other)
{
_width = other._width;
_height = other._height;
return *this;
}
Copying, Assignment, and Destruction
void f()
{
int x{1}; // x comes into existence
int y{2}; // y comes into existence
}

// y goes out of existence
// x goes out of existence
Destructor
• Name is always ~ plus the name of the class
– E.g., ~Rectangle()

• Returns nothing, takes no parameters
• Place to cleanup resources used by an object
– Close a file
– Release a lock
– Etc

• When exceptions transfer execution out of a scope,
everything declared in that scope is cleaned up
– Destructor runs
DEMO
RAII
Smart pointers
• unique_ptr if only one object needs access to the underlying
pointer
• shared_ptr if several want to use the same underlying pointer
– Cleaned up when the last copy goes out of scope

• In <memory> header file

• If you’re using new or delete, you’re doing it wrong
RAII in General
• Constructor acquires resource
– Eg opens file

• All other member functions know resource is acquired
– Do not need to test and make sure

• Destructor releases resource
– Works even in the presence of exceptions
Module Overview
1. Pointers
2. Dynamic Allocation
3. Exceptions
4. Copying, Assignment, and Destruction
5. Resource Acquisition is Initialization (RAII)
6. Smart Pointers
DEMO
Smart Pointers
©2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the
U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft
must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after
the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Contenu connexe

Tendances

Aftermath of functional programming. The good parts
Aftermath of functional programming. The good partsAftermath of functional programming. The good parts
Aftermath of functional programming. The good partsGuillermo Gutiérrez
 
Aftermath of functional programming. the good parts
Aftermath of functional programming. the good partsAftermath of functional programming. the good parts
Aftermath of functional programming. the good partsGuillermo Gutiérrez
 
Replace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeReplace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeAkira Takahashi
 
Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr-archana-dhawan-bajaj
 
11 abstract data types
11 abstract data types11 abstract data types
11 abstract data typesjigeno
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureJayaram Sankaranarayanan
 
C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructorDa Mystic Sadi
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMSfawzmasood
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
45 aop-programming
45 aop-programming45 aop-programming
45 aop-programmingdaotuan85
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...rapidbounce
 

Tendances (20)

iOS Basic
iOS BasiciOS Basic
iOS Basic
 
Aftermath of functional programming. The good parts
Aftermath of functional programming. The good partsAftermath of functional programming. The good parts
Aftermath of functional programming. The good parts
 
Aftermath of functional programming. the good parts
Aftermath of functional programming. the good partsAftermath of functional programming. the good parts
Aftermath of functional programming. the good parts
 
Generics In and Out
Generics In and OutGenerics In and Out
Generics In and Out
 
Replace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeReplace OutputIterator and Extend Range
Replace OutputIterator and Extend Range
 
Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slides
 
11 abstract data types
11 abstract data types11 abstract data types
11 abstract data types
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software Architecture
 
Idiomatic C++
Idiomatic C++Idiomatic C++
Idiomatic C++
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructor
 
Lecture6
Lecture6Lecture6
Lecture6
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
45 aop-programming
45 aop-programming45 aop-programming
45 aop-programming
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...
 
Namespaces
NamespacesNamespaces
Namespaces
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 

En vedette

06 the pipeline-deeper
06  the pipeline-deeper06  the pipeline-deeper
06 the pipeline-deeperShubham Atkare
 
09 automation in scale - remoting
09 automation in scale - remoting09 automation in scale - remoting
09 automation in scale - remotingShubham Atkare
 
10 introducing scripting and toolmaking
10 introducing scripting and toolmaking10 introducing scripting and toolmaking
10 introducing scripting and toolmakingShubham Atkare
 
08 getting prepared for automation
08  getting prepared for automation08  getting prepared for automation
08 getting prepared for automationShubham Atkare
 
07 the power in the shell - remoting
07 the power in the shell - remoting07 the power in the shell - remoting
07 the power in the shell - remotingShubham Atkare
 
Advanced C++ concepts
Advanced C++ conceptsAdvanced C++ concepts
Advanced C++ conceptseleksdev
 

En vedette (7)

06 the pipeline-deeper
06  the pipeline-deeper06  the pipeline-deeper
06 the pipeline-deeper
 
09 automation in scale - remoting
09 automation in scale - remoting09 automation in scale - remoting
09 automation in scale - remoting
 
10 introducing scripting and toolmaking
10 introducing scripting and toolmaking10 introducing scripting and toolmaking
10 introducing scripting and toolmaking
 
08 getting prepared for automation
08  getting prepared for automation08  getting prepared for automation
08 getting prepared for automation
 
07 the power in the shell - remoting
07 the power in the shell - remoting07 the power in the shell - remoting
07 the power in the shell - remoting
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
Advanced C++ concepts
Advanced C++ conceptsAdvanced C++ concepts
Advanced C++ concepts
 

Similaire à 5 raii

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 StructuresSelvaraj Seerangan
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2ppd1961
 
Industry - Program analysis and verification - Type-preserving Heap Profiler ...
Industry - Program analysis and verification - Type-preserving Heap Profiler ...Industry - Program analysis and verification - Type-preserving Heap Profiler ...
Industry - Program analysis and verification - Type-preserving Heap Profiler ...ICSM 2011
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting StartedHadziq Fabroyir
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...7mind
 
PHP Barcelona 2010 - Architecture and testability
PHP Barcelona 2010 - Architecture and testabilityPHP Barcelona 2010 - Architecture and testability
PHP Barcelona 2010 - Architecture and testabilityGiorgio Sironi
 
C++tutorial
C++tutorialC++tutorial
C++tutorialdips17
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
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
 

Similaire à 5 raii (20)

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
 
Bjarne essencegn13
Bjarne essencegn13Bjarne essencegn13
Bjarne essencegn13
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Industry - Program analysis and verification - Type-preserving Heap Profiler ...
Industry - Program analysis and verification - Type-preserving Heap Profiler ...Industry - Program analysis and verification - Type-preserving Heap Profiler ...
Industry - Program analysis and verification - Type-preserving Heap Profiler ...
 
Workshop on python
Workshop on pythonWorkshop on python
Workshop on python
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
 
PHP Barcelona 2010 - Architecture and testability
PHP Barcelona 2010 - Architecture and testabilityPHP Barcelona 2010 - Architecture and testability
PHP Barcelona 2010 - Architecture and testability
 
C++tutorial
C++tutorialC++tutorial
C++tutorial
 
06.1 .Net memory management
06.1 .Net memory management06.1 .Net memory management
06.1 .Net memory management
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
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)
 
Symbexecsearch
SymbexecsearchSymbexecsearch
Symbexecsearch
 
Function overloading
Function overloadingFunction overloading
Function overloading
 

Plus de Shubham Atkare

05 objects for the admin
05 objects for the admin05 objects for the admin
05 objects for the adminShubham Atkare
 
04 extending the shell
04 extending the shell04 extending the shell
04 extending the shellShubham Atkare
 
03 the pipeline-getting connected 1
03 the pipeline-getting connected 103 the pipeline-getting connected 1
03 the pipeline-getting connected 1Shubham Atkare
 
01 dont fear the shell 1
01 dont fear the shell 101 dont fear the shell 1
01 dont fear the shell 1Shubham Atkare
 
10 introducing scripting and toolmaking
10 introducing scripting and toolmaking10 introducing scripting and toolmaking
10 introducing scripting and toolmakingShubham Atkare
 

Plus de Shubham Atkare (7)

05 objects for the admin
05 objects for the admin05 objects for the admin
05 objects for the admin
 
04 extending the shell
04 extending the shell04 extending the shell
04 extending the shell
 
03 the pipeline-getting connected 1
03 the pipeline-getting connected 103 the pipeline-getting connected 1
03 the pipeline-getting connected 1
 
02 the help system
02 the help system02 the help system
02 the help system
 
01 dont fear the shell 1
01 dont fear the shell 101 dont fear the shell 1
01 dont fear the shell 1
 
10 introducing scripting and toolmaking
10 introducing scripting and toolmaking10 introducing scripting and toolmaking
10 introducing scripting and toolmaking
 
5 raii
5 raii5 raii
5 raii
 

Dernier

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 

Dernier (20)

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 

5 raii

  • 1. 05 | Pointers and RAII Kate Gregory | Gregory Consulting James McNellis | Senior Engineer, Visual C++
  • 2. Module Overview 1. Pointers 2. Dynamic Allocation 3. Exceptions 4. Copying, Assignment, and Destruction 5. Resource Acquisition is Initialization (RAII) 6. Smart Pointers
  • 3. Module Overview 1. Pointers 2. Dynamic Allocation 3. Exceptions 4. Copying, Assignment, and Destruction 5. Resource Acquisition is Initialization (RAII) 6. Smart Pointers
  • 4. Lesson 1: Pointers void f() { int x{1}; int y{2}; } … x y …
  • 5. Lesson 1: Pointers void f() { int x{1}; int y{2}; } &x … &y x y …
  • 6. Lesson 1: Pointers void f() { int x{1}; int y{2}; int* pointer_to_x{&x}; int* pointer_to_y{&y}; }
  • 7. Lesson 1: Pointers void f() { int x{1}; int* pointer_to_x{&x}; int y{*pointer_to_x}; }
  • 8. Lesson 1: Pointers void f() { int x{1}; int* pointer_to_x{&x}; *pointer_to_x = 2; }
  • 9. Lesson 1: Pointers void f() { int x{1}; int y{2}; int* p{&x}; p = &y; }
  • 10. Lesson 1: Pointers void f() { int p{nullptr}; }
  • 12. Module Overview 1. Pointers 2. Dynamic Allocation 3. Exceptions 4. Copying, Assignment, and Destruction 5. Resource Acquisition is Initialization (RAII) 6. Smart Pointers
  • 13. Lesson 2: Dynamic Allocation • Objects have scope, and go away when execution reaches the end of that scope void f() { NamedRectangle fred_rectangle{ "Fred", 3, 4 }; // . . . } • What if other code needed that object still?
  • 14. The Free Store • Separate area of memory • Objects created there stick around until deliberately cleaned up • To create one, use new – returns a pointer • To clean up, use delete
  • 15. The Free Store void f() { int* p{new int{1}}; *p = 2; delete p; }
  • 17. Module Overview 1. Pointers 2. Dynamic Allocation 3. Exceptions 4. Copying, Assignment, and Destruction 5. Resource Acquisition is Initialization (RAII) 6. Smart Pointers
  • 18. Exceptions • Sometimes what you want can’t be done – That file doesn’t exist any more – You don’t have permission to do that to the system • Checking in advance is best, but not always possible • Code that calls a function doesn’t need to check return value • C++ provides a non ignorable signal that something awful has happened • Will return from any nested level of function calls to a place that can handle the error
  • 19. Exception syntax try { // anything, including function calls } catch (const std::exception& e) { std::cout << "Exception caught: " << e.what(); }
  • 21. Module Overview 1. Pointers 2. Dynamic Allocation 3. Exceptions 4. Copying, Assignment, and Destruction 5. Resource Acquisition is Initialization (RAII) 6. Smart Pointers
  • 22. Copying, Assignment, and Destruction void f() { int x{1}; int y{x}; // Copying y = x; } // Assignment
  • 23. Copying, Assignment, and Destruction void f() { Rectangle x{3, 4}; Rectangle y{x}; // Copying y = x; } // Assignment
  • 24. Copying, Assignment, and Destruction • Copying a class-type object invokes a special constructor – Called the copy constructor – Rectangle(Rectangle const&); – If you don’t define one, the compiler provides one by default • The default behaviour is to copy each base and data member
  • 25. Copying, Assignment, and Destruction • Copying a class-type object invokes a special constructor – Called the copy constructor – Rectangle(Rectangle const&); – If you don’t define one, the compiler provides one by default • The default behaviour is to copy each base and data member Rectangle(Rectangle const& other) : _width{other._width}, _height{other._height}
  • 26. Copying, Assignment, and Destruction • Assigning to a class-type object invokes a special operator – Called the assignment operator – Rectangle& operator=(Rectangle const&); – If you don’t define one, the compiler provides one by default • The default behaviour is to assign each base and data member
  • 27. Copying, Assignment, and Destruction • Assigning to a class-type object invokes a special operator – Called the assignment operator – Rectangle& operator=(Rectangle const&); – If you don’t define one, the compiler provides one by default • The default behaviour is to assign each base and data member Rectangle& operator=(Rectangle const& other) { _width = other._width; _height = other._height; return *this; }
  • 28. Copying, Assignment, and Destruction void f() { int x{1}; // x comes into existence int y{2}; // y comes into existence } // y goes out of existence // x goes out of existence
  • 29. Destructor • Name is always ~ plus the name of the class – E.g., ~Rectangle() • Returns nothing, takes no parameters • Place to cleanup resources used by an object – Close a file – Release a lock – Etc • When exceptions transfer execution out of a scope, everything declared in that scope is cleaned up – Destructor runs
  • 31. Smart pointers • unique_ptr if only one object needs access to the underlying pointer • shared_ptr if several want to use the same underlying pointer – Cleaned up when the last copy goes out of scope • In <memory> header file • If you’re using new or delete, you’re doing it wrong
  • 32. RAII in General • Constructor acquires resource – Eg opens file • All other member functions know resource is acquired – Do not need to test and make sure • Destructor releases resource – Works even in the presence of exceptions
  • 33. Module Overview 1. Pointers 2. Dynamic Allocation 3. Exceptions 4. Copying, Assignment, and Destruction 5. Resource Acquisition is Initialization (RAII) 6. Smart Pointers
  • 35. ©2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.