SlideShare a Scribd company logo
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.

More Related Content

What's hot

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
Guillermo 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 parts
Guillermo Gutiérrez
 
Replace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeReplace OutputIterator and Extend Range
Replace OutputIterator and Extend Range
Akira 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 slides
Dr-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 Architecture
Jayaram Sankaranarayanan
 
Idiomatic C++
Idiomatic C++Idiomatic C++
Idiomatic C++
Federico Ficarelli
 
C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructor
Da Mystic Sadi
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
fawzmasood
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro 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 Answer
lavparmar007
 
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
 
Namespaces
NamespacesNamespaces
Namespaces
Sangeetha S
 

What's hot (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
 

Viewers also liked

Churchill and rise of hitler
Churchill and rise of hitlerChurchill and rise of hitler
Churchill and rise of hitlersgwmalcol
 
Mlk
MlkMlk
Concept Map 5b Baby L[1] (1)
Concept Map 5b Baby L[1] (1)Concept Map 5b Baby L[1] (1)
Concept Map 5b Baby L[1] (1)mafe
 
左轮扳机机制 戴维·安德森
左轮扳机机制  戴维·安德森左轮扳机机制  戴维·安德森
左轮扳机机制 戴维·安德森Jin Song
 
Music video-analysis-x3
Music video-analysis-x3Music video-analysis-x3
Music video-analysis-x3
Jack Allinson
 
Risk assessment form
Risk assessment formRisk assessment form
Risk assessment form
Jack Allinson
 
08 getting prepared for automation
08  getting prepared for automation08  getting prepared for automation
08 getting prepared for automationShubham 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
 
Shell project shipment 2013 part 2 zeebrugge
Shell project shipment 2013 part 2 zeebruggeShell project shipment 2013 part 2 zeebrugge
Shell project shipment 2013 part 2 zeebruggeDmitri Tchistov
 
Digipak analysis-x3
Digipak analysis-x3Digipak analysis-x3
Digipak analysis-x3
Jack Allinson
 
06 the pipeline-deeper
06  the pipeline-deeper06  the pipeline-deeper
06 the pipeline-deeperShubham 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
 
03 the pipeline-getting connected 1
03 the pipeline-getting connected 103 the pipeline-getting connected 1
03 the pipeline-getting connected 1Shubham Atkare
 
10 introducing scripting and toolmaking
10 introducing scripting and toolmaking10 introducing scripting and toolmaking
10 introducing scripting and toolmakingShubham Atkare
 
05 objects for the admin
05 objects for the admin05 objects for the admin
05 objects for the adminShubham Atkare
 
09 automation in scale - remoting
09 automation in scale - remoting09 automation in scale - remoting
09 automation in scale - remotingShubham Atkare
 
Правовое положение Антарктики
Правовое положение АнтарктикиПравовое положение Антарктики
Правовое положение АнтарктикиSlava199364
 

Viewers also liked (20)

Churchill and rise of hitler
Churchill and rise of hitlerChurchill and rise of hitler
Churchill and rise of hitler
 
Mlk
MlkMlk
Mlk
 
Jenlags
JenlagsJenlags
Jenlags
 
Concept Map 5b Baby L[1] (1)
Concept Map 5b Baby L[1] (1)Concept Map 5b Baby L[1] (1)
Concept Map 5b Baby L[1] (1)
 
左轮扳机机制 戴维·安德森
左轮扳机机制  戴维·安德森左轮扳机机制  戴维·安德森
左轮扳机机制 戴维·安德森
 
02 the help system
02 the help system02 the help system
02 the help system
 
Music video-analysis-x3
Music video-analysis-x3Music video-analysis-x3
Music video-analysis-x3
 
Risk assessment form
Risk assessment formRisk assessment form
Risk assessment form
 
08 getting prepared for automation
08  getting prepared for automation08  getting prepared for automation
08 getting prepared for automation
 
01 dont fear the shell 1
01 dont fear the shell 101 dont fear the shell 1
01 dont fear the shell 1
 
Shell project shipment 2013 part 2 zeebrugge
Shell project shipment 2013 part 2 zeebruggeShell project shipment 2013 part 2 zeebrugge
Shell project shipment 2013 part 2 zeebrugge
 
Digipak analysis-x3
Digipak analysis-x3Digipak analysis-x3
Digipak analysis-x3
 
5 raii
5 raii5 raii
5 raii
 
06 the pipeline-deeper
06  the pipeline-deeper06  the pipeline-deeper
06 the pipeline-deeper
 
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
 
03 the pipeline-getting connected 1
03 the pipeline-getting connected 103 the pipeline-getting connected 1
03 the pipeline-getting connected 1
 
10 introducing scripting and toolmaking
10 introducing scripting and toolmaking10 introducing scripting and toolmaking
10 introducing scripting and toolmaking
 
05 objects for the admin
05 objects for the admin05 objects for the admin
05 objects for the admin
 
09 automation in scale - remoting
09 automation in scale - remoting09 automation in scale - remoting
09 automation in scale - remoting
 
Правовое положение Антарктики
Правовое положение АнтарктикиПравовое положение Антарктики
Правовое положение Антарктики
 

Similar to 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 Structures
Selvaraj 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 2
ppd1961
 
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
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
Michael Redlich
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
Michael Redlich
 
#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 I
Eugene Lazutkin
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman 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 testability
Giorgio Sironi
 
C++tutorial
C++tutorialC++tutorial
C++tutorialdips17
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
Vishal Mahajan
 
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_patterns
amitarcade
 
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
 
Symbexecsearch
SymbexecsearchSymbexecsearch
Symbexecsearch
Abhik Roychoudhury
 

Similar to 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
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
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
 

Recently uploaded

Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 

Recently uploaded (20)

Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.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.