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

Unix/Linux Basic Commands and Shell Script
Unix/Linux Basic Commands and Shell ScriptUnix/Linux Basic Commands and Shell Script
Unix/Linux Basic Commands and Shell Scriptsbmguys
 
[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtooling[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtoolingDouglas Chen
 
Unix operating system architecture with file structure
Unix operating system architecture with file structure Unix operating system architecture with file structure
Unix operating system architecture with file structure amol_chavan
 
Operating system structures
Operating system structuresOperating system structures
Operating system structuresRahul Nagda
 
Symbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationSymbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationAkhil Kaushik
 
Java Presentation
Java PresentationJava Presentation
Java Presentationpm2214
 
Implementation of c string functions
Implementation of c string functionsImplementation of c string functions
Implementation of c string functionsmohamed sikander
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Geeks Anonymes
 
CMake - Introduction and best practices
CMake - Introduction and best practicesCMake - Introduction and best practices
CMake - Introduction and best practicesDaniel Pfeifer
 
Linux SMEP bypass techniques
Linux SMEP bypass techniquesLinux SMEP bypass techniques
Linux SMEP bypass techniquesVitaly Nikolenko
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notesRajiv Gupta
 

What's hot (20)

Unix/Linux Basic Commands and Shell Script
Unix/Linux Basic Commands and Shell ScriptUnix/Linux Basic Commands and Shell Script
Unix/Linux Basic Commands and Shell Script
 
Linux commands
Linux commandsLinux commands
Linux commands
 
Block Drivers
Block DriversBlock Drivers
Block Drivers
 
gcc and friends
gcc and friendsgcc and friends
gcc and friends
 
[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtooling[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtooling
 
BeagleBone Black Bootloaders
BeagleBone Black BootloadersBeagleBone Black Bootloaders
BeagleBone Black Bootloaders
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Unix operating system architecture with file structure
Unix operating system architecture with file structure Unix operating system architecture with file structure
Unix operating system architecture with file structure
 
Operating system structures
Operating system structuresOperating system structures
Operating system structures
 
Symbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationSymbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code Generation
 
U-Boot - An universal bootloader
U-Boot - An universal bootloader U-Boot - An universal bootloader
U-Boot - An universal bootloader
 
wrapper classes
wrapper classeswrapper classes
wrapper classes
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Variadic functions
Variadic functionsVariadic functions
Variadic functions
 
Implementation of c string functions
Implementation of c string functionsImplementation of c string functions
Implementation of c string functions
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
CMake - Introduction and best practices
CMake - Introduction and best practicesCMake - Introduction and best practices
CMake - Introduction and best practices
 
Linux SMEP bypass techniques
Linux SMEP bypass techniquesLinux SMEP bypass techniques
Linux SMEP bypass techniques
 
Kernel Debugging & Profiling
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & Profiling
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 

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

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 

Recently uploaded (20)

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 

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