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

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 

Último (20)

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 

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