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

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

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
 
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-x3Jack Allinson
 
Risk assessment form
Risk assessment formRisk assessment form
Risk assessment formJack 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
 
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 Pointers, RAII, and Smart Pointers in C

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
 

Similar to Pointers, RAII, and Smart Pointers in C (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

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 

Pointers, RAII, and Smart Pointers in C

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