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

Asterisk WebRTC frontier: realize client SIP Phone with sipML5 and Janus Gateway
Asterisk WebRTC frontier: realize client SIP Phone with sipML5 and Janus GatewayAsterisk WebRTC frontier: realize client SIP Phone with sipML5 and Janus Gateway
Asterisk WebRTC frontier: realize client SIP Phone with sipML5 and Janus GatewayAlessandro Polidori
 
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does ItAMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does ItNikhil Mittal
 
Aynchronous Processing in Kamailio Configuration File
Aynchronous Processing in Kamailio Configuration FileAynchronous Processing in Kamailio Configuration File
Aynchronous Processing in Kamailio Configuration FileDaniel-Constantin Mierla
 
A Kernel of Truth: Intrusion Detection and Attestation with eBPF
A Kernel of Truth: Intrusion Detection and Attestation with eBPFA Kernel of Truth: Intrusion Detection and Attestation with eBPF
A Kernel of Truth: Intrusion Detection and Attestation with eBPFoholiab
 
Command line arguments
Command line argumentsCommand line arguments
Command line argumentsAshok Raj
 
LAS16-504: Secure Storage updates in OP-TEE
LAS16-504: Secure Storage updates in OP-TEELAS16-504: Secure Storage updates in OP-TEE
LAS16-504: Secure Storage updates in OP-TEELinaro
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)Make Mannan
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelinesAnkur Goyal
 
DLM knowledge-sharing
DLM knowledge-sharingDLM knowledge-sharing
DLM knowledge-sharingEric Ren
 
Java Garbage Collection - How it works
Java Garbage Collection - How it worksJava Garbage Collection - How it works
Java Garbage Collection - How it worksMindfire Solutions
 
OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - PolymorphismMudasir Qazi
 
Page reclaim
Page reclaimPage reclaim
Page reclaimsiburu
 

What's hot (20)

Asterisk WebRTC frontier: realize client SIP Phone with sipML5 and Janus Gateway
Asterisk WebRTC frontier: realize client SIP Phone with sipML5 and Janus GatewayAsterisk WebRTC frontier: realize client SIP Phone with sipML5 and Janus Gateway
Asterisk WebRTC frontier: realize client SIP Phone with sipML5 and Janus Gateway
 
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does ItAMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
 
Aynchronous Processing in Kamailio Configuration File
Aynchronous Processing in Kamailio Configuration FileAynchronous Processing in Kamailio Configuration File
Aynchronous Processing in Kamailio Configuration File
 
A Kernel of Truth: Intrusion Detection and Attestation with eBPF
A Kernel of Truth: Intrusion Detection and Attestation with eBPFA Kernel of Truth: Intrusion Detection and Attestation with eBPF
A Kernel of Truth: Intrusion Detection and Attestation with eBPF
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Netcat - A Swiss Army Tool
Netcat - A Swiss Army ToolNetcat - A Swiss Army Tool
Netcat - A Swiss Army Tool
 
LAS16-504: Secure Storage updates in OP-TEE
LAS16-504: Secure Storage updates in OP-TEELAS16-504: Secure Storage updates in OP-TEE
LAS16-504: Secure Storage updates in OP-TEE
 
Character Drivers
Character DriversCharacter Drivers
Character Drivers
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
 
Wireshark
WiresharkWireshark
Wireshark
 
GTP Overview
GTP OverviewGTP Overview
GTP Overview
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
 
DLM knowledge-sharing
DLM knowledge-sharingDLM knowledge-sharing
DLM knowledge-sharing
 
Java Garbage Collection - How it works
Java Garbage Collection - How it worksJava Garbage Collection - How it works
Java Garbage Collection - How it works
 
OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - Polymorphism
 
Dpdk performance
Dpdk performanceDpdk performance
Dpdk performance
 
Java threads
Java threadsJava threads
Java threads
 
Page reclaim
Page reclaimPage reclaim
Page reclaim
 
Complejidad Algoritmica
Complejidad AlgoritmicaComplejidad Algoritmica
Complejidad Algoritmica
 

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

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
"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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
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
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
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
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
"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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
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
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
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
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

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