SlideShare a Scribd company logo
1 of 21
Download to read offline
“RESOURCE ACQUISITION
       IS INITIALIZATION”

                      Andrey Dankevich
                      April, 2013


1                            4/18/2013
What is a resource?

    •   Memory
    •   Handles
    •   Locks
    •   Sockets
    •   Threads
    •   Temp files
    •   …



2                                          4/18/2013
What is a resource?




    “Resource” is anything that follows this pattern!

3                                             4/18/2013
So what’s the problem?
    Real code might have different points at which
    the resource should be released:




4                                           4/18/2013
Resources and errors


    void f(const char* p)
    {
         FILE* f = fopen(p,"r"); // acquire
         // use f
         fclose(f); // release
    }




5                                         4/18/2013
Resources and errors
    // naïve fix:
    void f(const char* p)
    {                         Is this code really
       FILE* f = 0;
       try {
                                     safer?
          f = fopen(p, "r");
          // use f
       }
       catch (…) { // handle every exception
          if (f) fclose(f);
          throw;
       }
       if (f) fclose(f);
    }
6                                         4/18/2013
RAII
// use an object to represent a resource
class File_handle { // belongs in some support library
     FILE* p;
     public:
        File_handle(const char* pp, const char* r) {
          p = fopen(pp,r);
          if (p==0) throw File_error(pp,r);
        }

       File_handle(const string& s, const char* r) {
         p = fopen(s.c_str(),r);
         if (p==0) throw File_error(s,r); }

       ~File_handle() { fclose(p); }
};
7                                                4/18/2013
Stack lifetime semantics

In C++ the only code that can be guaranteed to be
executed after an exception is thrown are the destructors
of objects residing on the stack.
    Deterministic
    Exception-safe

         void f()
         {
            A a;
            throw 42;
         } // ~A() is called


8                                                 4/18/2013
LIVE DEMO

    http://ideone.com/enqHPr



9                              4/18/2013
.NET

•  Java, C# and Python, support various forms of the
  dispose pattern to simplify cleanup of resources.
• Custom classes in C# and Java have to explicitly
  implement the Dispose method.

     using (Font font1 = new Font("Arial", 10.0f))
     {
          byte charset = font1.GdiCharSet;
     }




10                                            4/18/2013
.NET

•  Java, C# and Python, support various forms of the
  dispose pattern to simplify cleanup of resources.
• Custom classes in C# and Java have to explicitly
  implement the Dispose method.
     {
         Font font1 = new Font("Arial", 10.0f);
         try {
               byte charset = font1.GdiCharSet;
         }
         finally {
               if (font1 != null)
                    ((IDisposable)font1).Dispose();
         }
11   }                                       4/18/2013
.NET - Examples
 Working with temp files:
     class TempFile : IDisposable {
          public TempFile(string filePath) {
              if (String.IsNullOrWhiteSpace(filePath))
                  throw new ArgumentNullException();
              this.Path = filePath;
          }
          public string Path { get; private set; }
          public void Dispose() {
              if (!String.IsNullOrWhiteSpace(this.Path)) {
                  try {
                      System.IO.File.Delete(this.Path);
                  } catch { }
                  this.Path = null;
              }
          }
12                                                    4/18/2013
      }
.NET - Examples

Working with temp settings values:

     Check the implementation for AutoCAD settings
     http://www.theswamp.org/index.php?topic=31897.msg474083#msg474083


Use this approach if you need to temporarily change the settings in
application.




13                                                             4/18/2013
Back to C++

Many STL classes use RAII:
     • std::basic_ifstream, std::basic_ofstream and
       std::basic_fstream will close the file stream on
       destruction if close() hasn’t yet been called.
     • smart pointer classes std::unique_ptr for single-owned
       objects and std::shared_ptr for objects with shared
       ownership.
     • Memory: std::string, std::vector…
     • Locks: std::unique_lock

14                                                    4/18/2013
SCOPE GUARD



15                 4/18/2013
SCOPE GUARD

• Original article: http://drdobbs.com/184403758
• Improved implementation:
   http://www.zete.org/people/jlehrer/scopeguard.html
• C++ and Beyond 2012: Andrei Alexandrescu - Systematic
  Error Handling in C++:
       video (from 01:05:11) - http://j.mp/XAbBWe
       slides ( from slide #31) - http://sdrv.ms/RXjNPR
• C++11 implementation:
   https://github.com/facebook/folly/blob/master/folly/ScopeGuard.h

                                                           4/18/2013
SCOPE GUARD vs unique_ptr

 Real-world example with PTC Creo API:
     • Resource type: ProReference
          In fact it’s mere a typedef void* ProReference;

     • Resource acquire:
        // Gets and allocates a ProReference containing a
        // representation for this selection.
        ProError ProSelectionToReference (ProSelection selection,
                                         ProReference* reference);

     • Resource release:
        ProError ProReferenceFree (ProReference reference);



17                                                            4/18/2013
SCOPE GUARD vs unique_ptr
     Using std::unique_ptr<>:
auto ref_allocator =
  []( const ProSelection selection ) -> ProReference {
     ProReference reference;
     ProError status = ProSelectionToReference(selection, &reference);
     return reference;
};
auto ref_deleter =
  [](ProReference& ref) {
     ProReferenceFree (ref);
};

std::unique_ptr
  <std::remove_pointer<ProReference>::type,
   decltype(ref_deleter)> fixed_surf_ref (
      ref_allocator(sels[0]),
      ref_deleter );
// ref_deleter is guaranteed to be called in destructor
18                                                          4/18/2013
SCOPE GUARD vs unique_ptr

 Using ScopeGuard:
     ProReference fixed_surf_ref = nullptr;
     status = ProSelectionToReference ( sels[0], &fixed_surf_ref );
     SCOPE_EXIT { ProReferenceFree ( fixed_surf_ref ); };




                   I LOVE IT!!!

19                                                            4/18/2013
http://j.mp/FridayTechTalks



20                           4/18/2013
Questions?




21                4/18/2013

More Related Content

What's hot

Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structureselliando dias
 
Terraform 0.12 Deep Dive: HCL 2.0 for Infrastructure as Code, Remote Plan & A...
Terraform 0.12 Deep Dive: HCL 2.0 for Infrastructure as Code, Remote Plan & A...Terraform 0.12 Deep Dive: HCL 2.0 for Infrastructure as Code, Remote Plan & A...
Terraform 0.12 Deep Dive: HCL 2.0 for Infrastructure as Code, Remote Plan & A...Mitchell Pronschinske
 
Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)Katy Slemon
 
Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Roman Elizarov
 
Nested structure (Computer programming and utilization)
Nested structure (Computer programming and utilization)Nested structure (Computer programming and utilization)
Nested structure (Computer programming and utilization)Digvijaysinh Gohil
 
Heap exploitation
Heap exploitationHeap exploitation
Heap exploitationAngel Boy
 
Linux Kernel - Virtual File System
Linux Kernel - Virtual File SystemLinux Kernel - Virtual File System
Linux Kernel - Virtual File SystemAdrian Huang
 
第2回勉強会スライド
第2回勉強会スライド第2回勉強会スライド
第2回勉強会スライドkoturn 0;
 
“Linux Kernel CPU Hotplug in the Multicore System”
“Linux Kernel CPU Hotplug in the Multicore System”“Linux Kernel CPU Hotplug in the Multicore System”
“Linux Kernel CPU Hotplug in the Multicore System”GlobalLogic Ukraine
 
Sigreturn Oriented Programming
Sigreturn Oriented ProgrammingSigreturn Oriented Programming
Sigreturn Oriented ProgrammingAngel Boy
 
Androidの入力システム
Androidの入力システムAndroidの入力システム
Androidの入力システムmagoroku Yamamoto
 
Bootiful Development with Spring Boot and Angular - Connect.Tech 2017
 Bootiful Development with Spring Boot and Angular - Connect.Tech 2017 Bootiful Development with Spring Boot and Angular - Connect.Tech 2017
Bootiful Development with Spring Boot and Angular - Connect.Tech 2017Matt Raible
 
좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012Daum DNA
 
Software update for embedded systems - elce2014
Software update for embedded systems - elce2014Software update for embedded systems - elce2014
Software update for embedded systems - elce2014Stefano Babic
 
Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018Roman Elizarov
 

What's hot (20)

Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Terraform 0.12 Deep Dive: HCL 2.0 for Infrastructure as Code, Remote Plan & A...
Terraform 0.12 Deep Dive: HCL 2.0 for Infrastructure as Code, Remote Plan & A...Terraform 0.12 Deep Dive: HCL 2.0 for Infrastructure as Code, Remote Plan & A...
Terraform 0.12 Deep Dive: HCL 2.0 for Infrastructure as Code, Remote Plan & A...
 
Deep C
Deep CDeep C
Deep C
 
Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)
 
Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
Nested structure (Computer programming and utilization)
Nested structure (Computer programming and utilization)Nested structure (Computer programming and utilization)
Nested structure (Computer programming and utilization)
 
Heap exploitation
Heap exploitationHeap exploitation
Heap exploitation
 
Io streams
Io streamsIo streams
Io streams
 
Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
 
Spring statemachine
Spring statemachineSpring statemachine
Spring statemachine
 
Linux Kernel - Virtual File System
Linux Kernel - Virtual File SystemLinux Kernel - Virtual File System
Linux Kernel - Virtual File System
 
第2回勉強会スライド
第2回勉強会スライド第2回勉強会スライド
第2回勉強会スライド
 
“Linux Kernel CPU Hotplug in the Multicore System”
“Linux Kernel CPU Hotplug in the Multicore System”“Linux Kernel CPU Hotplug in the Multicore System”
“Linux Kernel CPU Hotplug in the Multicore System”
 
Sigreturn Oriented Programming
Sigreturn Oriented ProgrammingSigreturn Oriented Programming
Sigreturn Oriented Programming
 
Androidの入力システム
Androidの入力システムAndroidの入力システム
Androidの入力システム
 
Bootiful Development with Spring Boot and Angular - Connect.Tech 2017
 Bootiful Development with Spring Boot and Angular - Connect.Tech 2017 Bootiful Development with Spring Boot and Angular - Connect.Tech 2017
Bootiful Development with Spring Boot and Angular - Connect.Tech 2017
 
좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012
 
Software update for embedded systems - elce2014
Software update for embedded systems - elce2014Software update for embedded systems - elce2014
Software update for embedded systems - elce2014
 
Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018
 

Viewers also liked

Presentation
PresentationPresentation
Presentationbugway
 
MedicReS Animal Experiments
MedicReS Animal ExperimentsMedicReS Animal Experiments
MedicReS Animal ExperimentsMedicReS
 
Infographic: The Dutch Games Market
Infographic: The Dutch Games MarketInfographic: The Dutch Games Market
Infographic: The Dutch Games MarketIngenico ePayments
 
2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubileeguestc8e3279
 
2010 bodley and blackwells
2010 bodley and blackwells2010 bodley and blackwells
2010 bodley and blackwellsRichard Ovenden
 
Presentation for Advanced Detection and Remote Sensing: Radar Systems
Presentation for Advanced Detection and Remote Sensing:  Radar SystemsPresentation for Advanced Detection and Remote Sensing:  Radar Systems
Presentation for Advanced Detection and Remote Sensing: Radar Systemsgtogtema
 
FactorEx - электронный факторинг
FactorEx - электронный факторинг FactorEx - электронный факторинг
FactorEx - электронный факторинг E-COM UA
 
James Caan Business Secrets App
James Caan Business Secrets AppJames Caan Business Secrets App
James Caan Business Secrets AppJamesCaan
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstractionSergey Platonov
 
Estilos y paradigmas de la Interacción Humano-Computador
Estilos y paradigmas de la Interacción Humano-ComputadorEstilos y paradigmas de la Interacción Humano-Computador
Estilos y paradigmas de la Interacción Humano-ComputadorPercy Negrete
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
How to manage Hortonworks HDB Resources with YARN
How to manage Hortonworks HDB Resources with YARNHow to manage Hortonworks HDB Resources with YARN
How to manage Hortonworks HDB Resources with YARNHortonworks
 
Unsupervised Feature Learning
Unsupervised Feature LearningUnsupervised Feature Learning
Unsupervised Feature LearningAmgad Muhammad
 
EMRでスポットインスタンスの自動入札ツールを作成する
EMRでスポットインスタンスの自動入札ツールを作成するEMRでスポットインスタンスの自動入札ツールを作成する
EMRでスポットインスタンスの自動入札ツールを作成するRecruit Technologies
 
Как обосновать затраты на ИБ?
Как обосновать затраты на ИБ?Как обосновать затраты на ИБ?
Как обосновать затраты на ИБ?Aleksey Lukatskiy
 
Microservice Architecture on AWS using AWS Lambda and Docker Containers
Microservice Architecture on AWS using AWS Lambda and Docker ContainersMicroservice Architecture on AWS using AWS Lambda and Docker Containers
Microservice Architecture on AWS using AWS Lambda and Docker ContainersDanilo Poccia
 
Customer Success Strategy Template
Customer Success Strategy TemplateCustomer Success Strategy Template
Customer Success Strategy TemplateOpsPanda
 

Viewers also liked (20)

Week10
Week10Week10
Week10
 
Presentation
PresentationPresentation
Presentation
 
JS patterns
JS patternsJS patterns
JS patterns
 
MedicReS Animal Experiments
MedicReS Animal ExperimentsMedicReS Animal Experiments
MedicReS Animal Experiments
 
Infographic: The Dutch Games Market
Infographic: The Dutch Games MarketInfographic: The Dutch Games Market
Infographic: The Dutch Games Market
 
2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee
 
2010 bodley and blackwells
2010 bodley and blackwells2010 bodley and blackwells
2010 bodley and blackwells
 
Presentation for Advanced Detection and Remote Sensing: Radar Systems
Presentation for Advanced Detection and Remote Sensing:  Radar SystemsPresentation for Advanced Detection and Remote Sensing:  Radar Systems
Presentation for Advanced Detection and Remote Sensing: Radar Systems
 
FactorEx - электронный факторинг
FactorEx - электронный факторинг FactorEx - электронный факторинг
FactorEx - электронный факторинг
 
James Caan Business Secrets App
James Caan Business Secrets AppJames Caan Business Secrets App
James Caan Business Secrets App
 
Cat's anatomy
Cat's anatomyCat's anatomy
Cat's anatomy
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
 
Estilos y paradigmas de la Interacción Humano-Computador
Estilos y paradigmas de la Interacción Humano-ComputadorEstilos y paradigmas de la Interacción Humano-Computador
Estilos y paradigmas de la Interacción Humano-Computador
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
How to manage Hortonworks HDB Resources with YARN
How to manage Hortonworks HDB Resources with YARNHow to manage Hortonworks HDB Resources with YARN
How to manage Hortonworks HDB Resources with YARN
 
Unsupervised Feature Learning
Unsupervised Feature LearningUnsupervised Feature Learning
Unsupervised Feature Learning
 
EMRでスポットインスタンスの自動入札ツールを作成する
EMRでスポットインスタンスの自動入札ツールを作成するEMRでスポットインスタンスの自動入札ツールを作成する
EMRでスポットインスタンスの自動入札ツールを作成する
 
Как обосновать затраты на ИБ?
Как обосновать затраты на ИБ?Как обосновать затраты на ИБ?
Как обосновать затраты на ИБ?
 
Microservice Architecture on AWS using AWS Lambda and Docker Containers
Microservice Architecture on AWS using AWS Lambda and Docker ContainersMicroservice Architecture on AWS using AWS Lambda and Docker Containers
Microservice Architecture on AWS using AWS Lambda and Docker Containers
 
Customer Success Strategy Template
Customer Success Strategy TemplateCustomer Success Strategy Template
Customer Success Strategy Template
 

Similar to RAII and ScopeGuard

Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionNate Abele
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityGeorgePeterBanyard
 
Configuration Surgery with Augeas
Configuration Surgery with AugeasConfiguration Surgery with Augeas
Configuration Surgery with AugeasPuppet
 
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...Dariusz Drobisz
 
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...Databricks
 
Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for DummiesElizabeth Smith
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
Android | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted NewardAndroid | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted NewardJAX London
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx FranceDavid Delabassee
 

Similar to RAII and ScopeGuard (20)

Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
core java
core javacore java
core java
 
File handling in C
File handling in CFile handling in C
File handling in C
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Configuration Surgery with Augeas
Configuration Surgery with AugeasConfiguration Surgery with Augeas
Configuration Surgery with Augeas
 
Augeas @RMLL 2012
Augeas @RMLL 2012Augeas @RMLL 2012
Augeas @RMLL 2012
 
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
 
Oop lecture9 12
Oop lecture9 12Oop lecture9 12
Oop lecture9 12
 
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
 
Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for Dummies
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
C++ idioms.pptx
C++ idioms.pptxC++ idioms.pptx
C++ idioms.pptx
 
Android | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted NewardAndroid | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted Neward
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France
 

Recently uploaded

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 

Recently uploaded (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 

RAII and ScopeGuard

  • 1. “RESOURCE ACQUISITION IS INITIALIZATION” Andrey Dankevich April, 2013 1 4/18/2013
  • 2. What is a resource? • Memory • Handles • Locks • Sockets • Threads • Temp files • … 2 4/18/2013
  • 3. What is a resource? “Resource” is anything that follows this pattern! 3 4/18/2013
  • 4. So what’s the problem? Real code might have different points at which the resource should be released: 4 4/18/2013
  • 5. Resources and errors void f(const char* p) { FILE* f = fopen(p,"r"); // acquire // use f fclose(f); // release } 5 4/18/2013
  • 6. Resources and errors // naïve fix: void f(const char* p) { Is this code really FILE* f = 0; try { safer? f = fopen(p, "r"); // use f } catch (…) { // handle every exception if (f) fclose(f); throw; } if (f) fclose(f); } 6 4/18/2013
  • 7. RAII // use an object to represent a resource class File_handle { // belongs in some support library FILE* p; public: File_handle(const char* pp, const char* r) { p = fopen(pp,r); if (p==0) throw File_error(pp,r); } File_handle(const string& s, const char* r) { p = fopen(s.c_str(),r); if (p==0) throw File_error(s,r); } ~File_handle() { fclose(p); } }; 7 4/18/2013
  • 8. Stack lifetime semantics In C++ the only code that can be guaranteed to be executed after an exception is thrown are the destructors of objects residing on the stack.  Deterministic  Exception-safe void f() { A a; throw 42; } // ~A() is called 8 4/18/2013
  • 9. LIVE DEMO http://ideone.com/enqHPr 9 4/18/2013
  • 10. .NET • Java, C# and Python, support various forms of the dispose pattern to simplify cleanup of resources. • Custom classes in C# and Java have to explicitly implement the Dispose method. using (Font font1 = new Font("Arial", 10.0f)) { byte charset = font1.GdiCharSet; } 10 4/18/2013
  • 11. .NET • Java, C# and Python, support various forms of the dispose pattern to simplify cleanup of resources. • Custom classes in C# and Java have to explicitly implement the Dispose method. { Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) ((IDisposable)font1).Dispose(); } 11 } 4/18/2013
  • 12. .NET - Examples Working with temp files: class TempFile : IDisposable { public TempFile(string filePath) { if (String.IsNullOrWhiteSpace(filePath)) throw new ArgumentNullException(); this.Path = filePath; } public string Path { get; private set; } public void Dispose() { if (!String.IsNullOrWhiteSpace(this.Path)) { try { System.IO.File.Delete(this.Path); } catch { } this.Path = null; } } 12 4/18/2013 }
  • 13. .NET - Examples Working with temp settings values: Check the implementation for AutoCAD settings http://www.theswamp.org/index.php?topic=31897.msg474083#msg474083 Use this approach if you need to temporarily change the settings in application. 13 4/18/2013
  • 14. Back to C++ Many STL classes use RAII: • std::basic_ifstream, std::basic_ofstream and std::basic_fstream will close the file stream on destruction if close() hasn’t yet been called. • smart pointer classes std::unique_ptr for single-owned objects and std::shared_ptr for objects with shared ownership. • Memory: std::string, std::vector… • Locks: std::unique_lock 14 4/18/2013
  • 15. SCOPE GUARD 15 4/18/2013
  • 16. SCOPE GUARD • Original article: http://drdobbs.com/184403758 • Improved implementation: http://www.zete.org/people/jlehrer/scopeguard.html • C++ and Beyond 2012: Andrei Alexandrescu - Systematic Error Handling in C++:  video (from 01:05:11) - http://j.mp/XAbBWe  slides ( from slide #31) - http://sdrv.ms/RXjNPR • C++11 implementation: https://github.com/facebook/folly/blob/master/folly/ScopeGuard.h 4/18/2013
  • 17. SCOPE GUARD vs unique_ptr Real-world example with PTC Creo API: • Resource type: ProReference In fact it’s mere a typedef void* ProReference; • Resource acquire: // Gets and allocates a ProReference containing a // representation for this selection. ProError ProSelectionToReference (ProSelection selection, ProReference* reference); • Resource release: ProError ProReferenceFree (ProReference reference); 17 4/18/2013
  • 18. SCOPE GUARD vs unique_ptr Using std::unique_ptr<>: auto ref_allocator = []( const ProSelection selection ) -> ProReference { ProReference reference; ProError status = ProSelectionToReference(selection, &reference); return reference; }; auto ref_deleter = [](ProReference& ref) { ProReferenceFree (ref); }; std::unique_ptr <std::remove_pointer<ProReference>::type, decltype(ref_deleter)> fixed_surf_ref ( ref_allocator(sels[0]), ref_deleter ); // ref_deleter is guaranteed to be called in destructor 18 4/18/2013
  • 19. SCOPE GUARD vs unique_ptr Using ScopeGuard: ProReference fixed_surf_ref = nullptr; status = ProSelectionToReference ( sels[0], &fixed_surf_ref ); SCOPE_EXIT { ProReferenceFree ( fixed_surf_ref ); }; I LOVE IT!!! 19 4/18/2013
  • 21. Questions? 21 4/18/2013