SlideShare uma empresa Scribd logo
1 de 12
Resource Acquisition Is
  Initialization (RAII)
{
    int device;

    if( . . . ) // Some selection criteria
    {
        device = open(. . .);
    } else {
        device = socket(. . .);
        . . .
    }

    close(device);
}
{
    int device;

    if( . . . ) // Some selection criteria
    {
        device = open(. . .);
    } else {
        device = socket(. . .);
        . . .
    }
    // If you return, or throw exception, here then device
    // remains open:

    // if ( . . . ) // close(device) was accidentally forgotten
    //    return;
    close(device);
}
struct DeviceCloser      {

     DeviceCloser()      // Initialization
        : m_device(NULL)
     {}

     ~DeviceCloser()    // Destruction
     {
       close(m_device); // Close the device handle
     }

     int m_device;
};
{
    DeviceCloser dc;
    int &device = dc.m_file;

    if( . . . ) // Some selection criteria
    {
        device = open(. . .);
    } else {
        device = socket(. . .);
        . . .
    }

    // … Whatever happens here, the device will be closed

} // Device closed here
struct DeviceCloser            {

     DeviceCloser(string device_name)               // Initialization
       //: m_device(NULL)
     {
         if( . . . ) // Some selection criteria
         {
             m_device = open(device_name, . . .);
         } else {
             m_device = socket(. . .);
             . . .
         }
     }

     ~DeviceCloser()    // Destruction
     {
       close(m_device); // Close the device handle
     }
     int m_device;
};
{
    string device_name(“Large Hadron Collider”);

    DeviceCloser dc(device_name);

    dc.start();

    // … Whatever happens here, the device will be closed
    // and the world will be saved

} // Device closed here
Object lifecycle




Construction       Acquire


                             Resource




 Destruction       Release
// in the the C language, see."cleanup" variable attribute”
#define RAII_VARIABLE(vartype,varname,initval,dtor) 
    void _dtor_ ## varname (vartype * v) { dtor(*v); } 
    vartype varname __attribute__((cleanup(_dtor_ ##
varname))) = (initval)

// This macro can then be used as follows:

void example_usage() {
  RAII_VARIABLE(FILE*, logfile, fopen("logfile.txt", "w+"),
fclose);
  fputs("hello logfile!", logfile);
}
Typical Uses

• Synchronization primitives
  (Mutex Lock/Unlock)
• File Open/Close
• Memory allocation/deallocation
Things to Remember

• To prevent resource leaks, use RAII objects
  that acquire resources in their constructors
  and release them in their destructors.
• Commonly useful RAII classes are
  shared_ptr,auto_ptr, etc[code] (another
  seminar)
List of references:
• Scott Meyers, Effective C++: 55 Specific Ways
  to Improve Your Programs and Designs
• Stephen C. Dewhurst, C++ Common
  Knowledge: Essential Intermediate
  Programming
• Matthew Wilson, Imperfect C++: Practical
  Solutions for Real-Life Programming

Mais conteúdo relacionado

Destaque

Developing an Education Social Media Strategy, NWAIS Seattle, 6/17/2014
Developing an Education Social Media Strategy, NWAIS Seattle, 6/17/2014Developing an Education Social Media Strategy, NWAIS Seattle, 6/17/2014
Developing an Education Social Media Strategy, NWAIS Seattle, 6/17/2014burma999
 
Anntech New Profile Modified 28042012
Anntech New Profile Modified 28042012Anntech New Profile Modified 28042012
Anntech New Profile Modified 28042012ashokanp
 
Bully free zone power point
Bully free zone power pointBully free zone power point
Bully free zone power pointlethalweapon
 
Leadership
LeadershipLeadership
Leadershipfjahan
 
มโนท ศน เทคโนโลย_ทางการศ_กษา
มโนท ศน เทคโนโลย_ทางการศ_กษามโนท ศน เทคโนโลย_ทางการศ_กษา
มโนท ศน เทคโนโลย_ทางการศ_กษาJulalak Kaewjoonla
 
Vizbi 2014 Multiscale Visualization of Protein Assemblies
Vizbi 2014 Multiscale Visualization of Protein AssembliesVizbi 2014 Multiscale Visualization of Protein Assemblies
Vizbi 2014 Multiscale Visualization of Protein AssembliesAndreas Prlić
 

Destaque (14)

Köklere Kültürel Yolculuk
Köklere Kültürel YolculukKöklere Kültürel Yolculuk
Köklere Kültürel Yolculuk
 
Researh
ResearhResearh
Researh
 
Eresume1
Eresume1Eresume1
Eresume1
 
Developing an Education Social Media Strategy, NWAIS Seattle, 6/17/2014
Developing an Education Social Media Strategy, NWAIS Seattle, 6/17/2014Developing an Education Social Media Strategy, NWAIS Seattle, 6/17/2014
Developing an Education Social Media Strategy, NWAIS Seattle, 6/17/2014
 
ข้อสอบ
ข้อสอบข้อสอบ
ข้อสอบ
 
Anntech New Profile Modified 28042012
Anntech New Profile Modified 28042012Anntech New Profile Modified 28042012
Anntech New Profile Modified 28042012
 
Bully free zone power point
Bully free zone power pointBully free zone power point
Bully free zone power point
 
Medicine Cabinet
Medicine CabinetMedicine Cabinet
Medicine Cabinet
 
Leadership
LeadershipLeadership
Leadership
 
Taxonomy summarized
Taxonomy summarizedTaxonomy summarized
Taxonomy summarized
 
มโนท ศน เทคโนโลย_ทางการศ_กษา
มโนท ศน เทคโนโลย_ทางการศ_กษามโนท ศน เทคโนโลย_ทางการศ_กษา
มโนท ศน เทคโนโลย_ทางการศ_กษา
 
01
0101
01
 
Vizbi 2014 Multiscale Visualization of Protein Assemblies
Vizbi 2014 Multiscale Visualization of Protein AssembliesVizbi 2014 Multiscale Visualization of Protein Assemblies
Vizbi 2014 Multiscale Visualization of Protein Assemblies
 
Multimedia 2012
Multimedia 2012Multimedia 2012
Multimedia 2012
 

Semelhante a Raii

Putting a Fork in Fork (Linux Process and Memory Management)
Putting a Fork in Fork (Linux Process and Memory Management)Putting a Fork in Fork (Linux Process and Memory Management)
Putting a Fork in Fork (Linux Process and Memory Management)David Evans
 
History & Practices for UniRx(EN)
History & Practices for UniRx(EN)History & Practices for UniRx(EN)
History & Practices for UniRx(EN)Yoshifumi Kawai
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdffederaleyecare
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAbimbola Idowu
 
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
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdfTamiratDejene1
 
Core java concepts
Core java concepts Core java concepts
Core java concepts javeed_mhd
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 

Semelhante a Raii (20)

Fault tolerance made easy
Fault tolerance made easyFault tolerance made easy
Fault tolerance made easy
 
Putting a Fork in Fork (Linux Process and Memory Management)
Putting a Fork in Fork (Linux Process and Memory Management)Putting a Fork in Fork (Linux Process and Memory Management)
Putting a Fork in Fork (Linux Process and Memory Management)
 
History & Practices for UniRx(EN)
History & Practices for UniRx(EN)History & Practices for UniRx(EN)
History & Practices for UniRx(EN)
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdf
 
RAII and ScopeGuard
RAII and ScopeGuardRAII and ScopeGuard
RAII and ScopeGuard
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
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
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdf
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Oop lecture9 12
Oop lecture9 12Oop lecture9 12
Oop lecture9 12
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Core Java
Core JavaCore Java
Core Java
 
srgoc
srgocsrgoc
srgoc
 
C++ idioms.pptx
C++ idioms.pptxC++ idioms.pptx
C++ idioms.pptx
 

Último

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Último (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

Raii

  • 1. Resource Acquisition Is Initialization (RAII)
  • 2. { int device; if( . . . ) // Some selection criteria { device = open(. . .); } else { device = socket(. . .); . . . } close(device); }
  • 3. { int device; if( . . . ) // Some selection criteria { device = open(. . .); } else { device = socket(. . .); . . . } // If you return, or throw exception, here then device // remains open: // if ( . . . ) // close(device) was accidentally forgotten // return; close(device); }
  • 4. struct DeviceCloser { DeviceCloser() // Initialization : m_device(NULL) {} ~DeviceCloser() // Destruction { close(m_device); // Close the device handle } int m_device; };
  • 5. { DeviceCloser dc; int &device = dc.m_file; if( . . . ) // Some selection criteria { device = open(. . .); } else { device = socket(. . .); . . . } // … Whatever happens here, the device will be closed } // Device closed here
  • 6. struct DeviceCloser { DeviceCloser(string device_name) // Initialization //: m_device(NULL) { if( . . . ) // Some selection criteria { m_device = open(device_name, . . .); } else { m_device = socket(. . .); . . . } } ~DeviceCloser() // Destruction { close(m_device); // Close the device handle } int m_device; };
  • 7. { string device_name(“Large Hadron Collider”); DeviceCloser dc(device_name); dc.start(); // … Whatever happens here, the device will be closed // and the world will be saved } // Device closed here
  • 8. Object lifecycle Construction Acquire Resource Destruction Release
  • 9. // in the the C language, see."cleanup" variable attribute” #define RAII_VARIABLE(vartype,varname,initval,dtor) void _dtor_ ## varname (vartype * v) { dtor(*v); } vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval) // This macro can then be used as follows: void example_usage() { RAII_VARIABLE(FILE*, logfile, fopen("logfile.txt", "w+"), fclose); fputs("hello logfile!", logfile); }
  • 10. Typical Uses • Synchronization primitives (Mutex Lock/Unlock) • File Open/Close • Memory allocation/deallocation
  • 11. Things to Remember • To prevent resource leaks, use RAII objects that acquire resources in their constructors and release them in their destructors. • Commonly useful RAII classes are shared_ptr,auto_ptr, etc[code] (another seminar)
  • 12. List of references: • Scott Meyers, Effective C++: 55 Specific Ways to Improve Your Programs and Designs • Stephen C. Dewhurst, C++ Common Knowledge: Essential Intermediate Programming • Matthew Wilson, Imperfect C++: Practical Solutions for Real-Life Programming