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

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
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
Vishal Mahajan
 
Advanced C++ concepts
Advanced C++ conceptsAdvanced C++ concepts
Advanced C++ concepts
eleksdev
 

Viewers also liked (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
 

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
 
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
 
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
 

More from 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
 

More from 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
 

Recently uploaded

Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
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
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Ashish Kohli
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
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
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
NelTorrente
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
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
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 

Recently uploaded (20)

Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
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
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
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...
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 

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.