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

Spark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud IbrahimovSpark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud IbrahimovMaksud Ibrahimov
 
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...Databricks
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 
Infrastructure testing with Molecule and TestInfra
Infrastructure testing with Molecule and TestInfraInfrastructure testing with Molecule and TestInfra
Infrastructure testing with Molecule and TestInfraTomislav Plavcic
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBrendan Gregg
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in RustInfluxData
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
Spark autotuning talk final
Spark autotuning talk finalSpark autotuning talk final
Spark autotuning talk finalRachel Warren
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performancePostgreSQL-Consulting
 
PostgreSQL + pgpool構成におけるリカバリ
PostgreSQL + pgpool構成におけるリカバリPostgreSQL + pgpool構成におけるリカバリ
PostgreSQL + pgpool構成におけるリカバリhiroin0
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Kernel Recipes 2017: Using Linux perf at Netflix
Kernel Recipes 2017: Using Linux perf at NetflixKernel Recipes 2017: Using Linux perf at Netflix
Kernel Recipes 2017: Using Linux perf at NetflixBrendan Gregg
 
Managing Apache Spark Workload and Automatic Optimizing
Managing Apache Spark Workload and Automatic OptimizingManaging Apache Spark Workload and Automatic Optimizing
Managing Apache Spark Workload and Automatic OptimizingDatabricks
 
Kernel Recipes 2019 - Faster IO through io_uring
Kernel Recipes 2019 - Faster IO through io_uringKernel Recipes 2019 - Faster IO through io_uring
Kernel Recipes 2019 - Faster IO through io_uringAnne Nicolas
 
Fine Tuning and Enhancing Performance of Apache Spark Jobs
Fine Tuning and Enhancing Performance of Apache Spark JobsFine Tuning and Enhancing Performance of Apache Spark Jobs
Fine Tuning and Enhancing Performance of Apache Spark JobsDatabricks
 
What is New with Apache Spark Performance Monitoring in Spark 3.0
What is New with Apache Spark Performance Monitoring in Spark 3.0What is New with Apache Spark Performance Monitoring in Spark 3.0
What is New with Apache Spark Performance Monitoring in Spark 3.0Databricks
 
Tomcatの実装から学ぶクラスローダリーク #渋谷Java
Tomcatの実装から学ぶクラスローダリーク #渋谷JavaTomcatの実装から学ぶクラスローダリーク #渋谷Java
Tomcatの実装から学ぶクラスローダリーク #渋谷JavaNorito Agetsuma
 
Spring Framework ふりかえりと4.3新機能
Spring Framework ふりかえりと4.3新機能Spring Framework ふりかえりと4.3新機能
Spring Framework ふりかえりと4.3新機能kimulla
 
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...yoshimotot
 

What's hot (20)

Spark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud IbrahimovSpark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud Ibrahimov
 
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Infrastructure testing with Molecule and TestInfra
Infrastructure testing with Molecule and TestInfraInfrastructure testing with Molecule and TestInfra
Infrastructure testing with Molecule and TestInfra
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame Graphs
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in Rust
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Spark autotuning talk final
Spark autotuning talk finalSpark autotuning talk final
Spark autotuning talk final
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performance
 
PostgreSQL + pgpool構成におけるリカバリ
PostgreSQL + pgpool構成におけるリカバリPostgreSQL + pgpool構成におけるリカバリ
PostgreSQL + pgpool構成におけるリカバリ
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Kernel Recipes 2017: Using Linux perf at Netflix
Kernel Recipes 2017: Using Linux perf at NetflixKernel Recipes 2017: Using Linux perf at Netflix
Kernel Recipes 2017: Using Linux perf at Netflix
 
Managing Apache Spark Workload and Automatic Optimizing
Managing Apache Spark Workload and Automatic OptimizingManaging Apache Spark Workload and Automatic Optimizing
Managing Apache Spark Workload and Automatic Optimizing
 
Kernel Recipes 2019 - Faster IO through io_uring
Kernel Recipes 2019 - Faster IO through io_uringKernel Recipes 2019 - Faster IO through io_uring
Kernel Recipes 2019 - Faster IO through io_uring
 
Fine Tuning and Enhancing Performance of Apache Spark Jobs
Fine Tuning and Enhancing Performance of Apache Spark JobsFine Tuning and Enhancing Performance of Apache Spark Jobs
Fine Tuning and Enhancing Performance of Apache Spark Jobs
 
What is New with Apache Spark Performance Monitoring in Spark 3.0
What is New with Apache Spark Performance Monitoring in Spark 3.0What is New with Apache Spark Performance Monitoring in Spark 3.0
What is New with Apache Spark Performance Monitoring in Spark 3.0
 
Tomcatの実装から学ぶクラスローダリーク #渋谷Java
Tomcatの実装から学ぶクラスローダリーク #渋谷JavaTomcatの実装から学ぶクラスローダリーク #渋谷Java
Tomcatの実装から学ぶクラスローダリーク #渋谷Java
 
Spring Framework ふりかえりと4.3新機能
Spring Framework ふりかえりと4.3新機能Spring Framework ふりかえりと4.3新機能
Spring Framework ふりかえりと4.3新機能
 
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
 

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

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Recently uploaded (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

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