Resource acquisition is initialization

Resource acquisition is initialization (RAII)[1] is a programming idiom[2] used in several object-oriented, statically typed programming languages to describe a particular language behavior. In RAII, holding a resource is a class invariant, and is tied to object lifetime. Resource allocation (or acquisition) is done during object creation (specifically initialization), by the constructor, while resource deallocation (release) is done during object destruction (specifically finalization), by the destructor. In other words, resource acquisition must succeed for initialization to succeed. Thus, the resource is guaranteed to be held between when initialization finishes and finalization starts (holding the resources is a class invariant), and to be held only when the object is alive. Thus, if there are no object leaks, there are no resource leaks.

RAII is associated most prominently with C++, where it originated, but also Ada,[3] Vala,[4] and Rust.[5] The technique was developed for exception-safe resource management in C++[6] during 1984–89, primarily by Bjarne Stroustrup and Andrew Koenig,[7] and the term itself was coined by Stroustrup.[8]

Other names for this idiom include Constructor Acquires, Destructor Releases (CADRe)[9] and one particular style of use is called Scope-based Resource Management (SBRM).[10] This latter term is for the special case of automatic variables. RAII ties resources to object lifetime, which may not coincide with entry and exit of a scope. (Notably variables allocated on the free store have lifetimes unrelated to any given scope.) However, using RAII for automatic variables (SBRM) is the most common use case.

C++11 example

The following C++11 example demonstrates usage of RAII for file access and mutex locking:

#include <fstream>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <string>

void WriteToFile(const std::string& message) {
  // |mutex| is to protect access to |file| (which is shared across threads).
  static std::mutex mutex;

  // Lock |mutex| before accessing |file|.
  std::lock_guard<std::mutex> lock(mutex);

  // Try to open file.
  std::ofstream file("example.txt");
  if (!file.is_open()) {
    throw std::runtime_error("unable to open file");
  }

  // Write |message| to |file|.
  file << message << std::endl;

  // |file| will be closed first when leaving scope (regardless of exception)
  // |mutex| will be unlocked second (from |lock| destructor) when leaving scope
  // (regardless of exception).
}

This code is exception-safe because C++ guarantees that all objects with automatic storage duration (local variables) are destroyed at the end of the enclosing scope in the reverse order of their construction.[11] The destructors of both the lock and file objects are therefore guaranteed to be called when returning from the function, whether an exception has been thrown or not.[12]

Local variables allow easy management of multiple resources within a single function: they are destroyed in the reverse order of their construction, and an object is destroyed only if fully constructed—that is, if no exception propagates from its constructor.[13]

Using RAII greatly simplifies resource management, reduces overall code size and helps ensure program correctness. RAII is therefore recommended by industry-standard guidelines,[14] and most of the C++ standard library follows the idiom.[15]

Benefits

The advantages of RAII as a resource management technique are that it provides encapsulation, exception safety (for stack resources), and locality (it allows acquisition and release logic to be written next to each other).

Encapsulation is provided because resource management logic is defined once in the class, not at each call site. Exception safety is provided for stack resources (resources that are released in the same scope as they are acquired) by tying the resource to the lifetime of a stack variable (a local variable declared in a given scope): if an exception is thrown, and proper exception handling is in place, the only code that will be executed when exiting the current scope are the destructors of objects declared in that scope. Finally, locality of definition is provided by writing the constructor and destructor definitions next to each other in the class definition.

Resource management therefore needs to be tied to the lifespan of suitable objects in order to gain automatic allocation and reclamation. Resources are acquired during initialization, when there is no chance of them being used before they are available, and released with the destruction of the same objects, which is guaranteed to take place even in case of errors.

Comparing RAII with the finally construct used in Java, Stroustrup wrote that “In realistic systems, there are far more resource acquisitions than kinds of resources, so the 'resource acquisition is initialization' technique leads to less code than use of a 'finally' construct.”[1]

Typical uses

The RAII design is often used for controlling mutex locks in multi-threaded applications. In that use, the object releases the lock when destroyed. Without RAII in this scenario the potential for deadlock would be high and the logic to lock the mutex would be far from the logic to unlock it. With RAII, the code that locks the mutex essentially includes the logic that the lock will be released when execution leaves the scope of the RAII object.

Another typical example is interacting with files: We could have an object that represents a file that is open for writing, wherein the file is opened in the constructor and closed when execution leaves the object's scope. In both cases, RAII ensures only that the resource in question is released appropriately; care must still be taken to maintain exception safety. If the code modifying the data structure or file is not exception-safe, the mutex could be unlocked or the file closed with the data structure or file corrupted.

Ownership of dynamically allocated objects (memory allocated with new in C++) can also be controlled with RAII, such that the object is released when the RAII (stack-based) object is destroyed. For this purpose, the C++11 standard library defines the smart pointer classes std::unique_ptr for single-owned objects and std::shared_ptr for objects with shared ownership. Similar classes are also available through std::auto_ptr in C++98, and boost::shared_ptr in the Boost libraries.

Also, messages can be sent to network resources using RAII. In this case, the RAII object would send a message to a socket at the end of the constructor, when its initialization is completed. It would also send a message at the beginning of the destructor, when the object is about to be destroyed. Such a construct might be used in a client object to establish a connection with a server running in another process.

Compiler "cleanup" extensions

Both Clang and the GNU Compiler Collection implement a non-standard extension to the C language to support RAII: the "cleanup" variable attribute.[16] The following annotates a variable with a given destructor function that it will call when the variable goes out of scope:

void example_usage() {
  __attribute__((cleanup(fclosep))) FILE *logfile = fopen("logfile.txt", "w+");
  fputs("hello logfile!", logfile);
}

In this example, the compiler arranges for the fclosep function to be called on logfile before example_usage returns.

Limitations

RAII only works for resources acquired and released (directly or indirectly) by stack-allocated objects, where there is a well-defined static object lifetime. Heap-allocated objects which themselves acquire and release resources are common in many languages, including C++. RAII depends on heap-based objects to be implicitly or explicitly deleted along all possible execution paths, in order to trigger its resource-releasing destructor (or equivalent).[17]: 8:27  This can be achieved by using smart pointers to manage all heap objects, with weak pointers for cyclically referenced objects.

In C++, stack unwinding is only guaranteed to occur if the exception is caught somewhere. This is because "If no matching handler is found in a program, the function terminate() is called; whether or not the stack is unwound before this call to terminate() is implementation-defined (15.5.1)." (C++03 standard, §15.3/9).[18] This behavior is usually acceptable, since the operating system releases remaining resources like memory, files, sockets, etc. at program termination.[citation needed]

At the 2018 Gamelab conference, Jonathan Blow explained how use of RAII can cause memory fragmentation which in turn can cause cache misses and a 100 times or worse hit on performance.[19]

Reference counting

Perl, Python (in the CPython implementation),[20] and PHP[21] manage object lifetime by reference counting, which makes it possible to use RAII. Objects that are no longer referenced are immediately destroyed or finalized and released, so a destructor or finalizer can release the resource at that time. However, it is not always idiomatic in such languages, and is specifically discouraged in Python (in favor of context managers and finalizers from the weakref package).[citation needed]

However, object lifetimes are not necessarily bound to any scope, and objects may be destroyed non-deterministically or not at all. This makes it possible to accidentally leak resources that should have been released at the end of some scope. Objects stored in a static variable (notably a global variable) may not be finalized when the program terminates, so their resources are not released; CPython makes no guarantee of finalizing such objects, for instance. Further, objects with circular references will not be collected by a simple reference counter, and will live indeterminately long; even if collected (by more sophisticated garbage collection), destruction time and destruction order will be non-deterministic. In CPython there is a cycle detector which detects cycles and finalizes the objects in the cycle, though prior to CPython 3.4, cycles are not collected if any object in the cycle has a finalizer.[22]

References

  1. ^ a b Stroustrup, Bjarne (2017-09-30). "Why doesn't C++ provide a "finally" construct?". Retrieved 2019-03-09.
  2. ^ Sutter, Herb; Alexandrescu, Andrei (2005). C++ Coding Standards. C++ In-Depth Series. Addison-Wesley. p. 24. ISBN 978-0-321-11358-0.
  3. ^ "Gem #70: The Scope Locks Idiom". AdaCore. Retrieved 21 May 2021.
  4. ^ The Valadate Project. "Destruction". The Vala Tutorial version 0.30. Retrieved 21 May 2021.
  5. ^ "RAII - Rust By Example". doc.rust-lang.org. Retrieved 2020-11-22.
  6. ^ Stroustrup 1994, 16.5 Resource Management, pp. 388–89.
  7. ^ Stroustrup 1994, 16.1 Exception Handling: Introduction, pp. 383–84.
  8. ^ Stroustrup 1994, p. 389. I called this technique "resource acquisition is initialization."
  9. ^ Arthur Tchaikovsky (2012-11-06). "Change official RAII to CADRe". ISO C++ Standard - Future Proposals. Google Groups. Retrieved 2019-03-09.
  10. ^ Chou, Allen (2014-10-01). "Scope-Based Resource Management (RAII)". Retrieved 2019-03-09.
  11. ^ Richard Smith (2017-03-21). "Working Draft, Standard for Programming Language C++" (PDF). p. 151, section §9.6. Retrieved 2023-09-07.
  12. ^ "How can I handle a destructor that fails?". Standard C++ Foundation. Retrieved 2019-03-09.
  13. ^ Richard Smith (2017-03-21). "Working Draft, Standard for Programming Language C++" (PDF). Retrieved 2019-03-09.
  14. ^ Stroustrup, Bjarne; Sutter, Herb (2020-08-03). "C++ Core Guidelines". Retrieved 2020-08-15.
  15. ^ "I have too many try blocks; what can I do about it?". Standard C++ Foundation. Retrieved 2019-03-09.
  16. ^ "Specifying Attributes of Variables". Using the GNU Compiler Collection (GCC). GNU Project. Retrieved 2019-03-09.
  17. ^ Weimer, Westley; Necula, George C. (2008). "Exceptional Situations and Program Reliability" (PDF). ACM Transactions on Programming Languages and Systems. Vol. 30, no. 2.
  18. ^ ildjarn (2011-04-05). "RAII and Stack unwinding". Stack Overflow. Retrieved 2019-03-09.
  19. ^ Gamelab2018 - Jon Blow's Design decisions on creating Jai a new language for game programmers on YouTube
  20. ^ "Extending Python with C or C++: Reference Counts". Extending and Embedding the Python Interpreter. Python Software Foundation. Retrieved 2019-03-09.
  21. ^ hobbs (2011-02-08). "Does PHP support the RAII pattern? How?". Retrieved 2019-03-09.
  22. ^ "gc — Garbage Collector interface". The Python Standard Library. Python Software Foundation. Retrieved 2019-03-09.

Further reading

Read other articles:

Voice of a Tortured SkullAlbum studio karya MayhemDirilis1986GenreBlack metalDurasi15:02Kronologi Mayhem Voice of a Tortured Skull(1986) Pure Fucking Armageddon(1986)Pure Fucking Armageddon1986 Voice of a Tortured Skull adalah album demo kelompok black metal Norwegia Mayhem. Daftar lagu Voice of a Tortured Skull – 2:22 Carnage – 4:14 Ghoul – 3:31 Black Metal – 2:06 (Venom Cover) Pure Fucking Armageddon – 2:49 Anggota Euronymous (Øystein Aarseth) - Guitar, Vocals Necrobutcher (J...

 

 

Kastel Urquhart Dekat Drumnadrochit, Skotlandia Kastil Urquhart dan Loch Ness Kastil Urquhart Koordinat 57°19′26″N 4°26′31″W / 57.324°N 4.442°W / 57.324; -4.442Koordinat: 57°19′26″N 4°26′31″W / 57.324°N 4.442°W / 57.324; -4.442 Dibangun Abad ke-13 hingga ke-16 Digunakan Hingga 1692 Kondisisaat ini Reruntuhan Pemiliksaat ini Historic Scotland Dibukauntuk umum Yes Kastil Urquhart, Menara Grant Kastel Urquhart (listen�...

 

 

Ełk Ełk (Jerman: Lyckcode: de is deprecated ) ialah kota di Polandia utara di provinsi Warmia-Mazury. Ibu kotanya adalah Powiat Ełk. koordinat geografi: 53° 29' N 22° 21' E penduduk: 61.523 (2017) wilayah: 19,7 km² Pranala luar Wikimedia Commons memiliki media mengenai Ełk. Situs resmi Diarsipkan 2018-01-26 di Wayback Machine. lbsPowiat EłkKotaEłk (ibu kota)GminaEłk • Kalinowo • Prostki • Stare Juchy Artikel bertopik geografi atau tempat Polandia ini adalah sebuah rintisa...

George VancouverLahir(1757-06-22)22 Juni 1757King's Lynn, Norfolk, EnglandMeninggal10 Mei 1798(1798-05-10) (umur 40)Petersham, Surrey, EnglandPekerjaanPerwira Angkatan LautTanda tangan Kapten George Vancouver RN (22 Juni 1757 – 10 Mei 1798) adalah seorang perwira Inggris dari Angkatan Laut Britania Raya, yang terkenal dengan ekspedisi 1791-95, yang menjelajahi dan memetakan wilayah Pantai Pasifik barat laut Amerika Utara, termasuk pantai-pantai Alaska, British Columbia, ...

 

 

سيشن تقسيم إداري البلد اليونان  [1] إحداثيات 35°18′25″N 25°31′24″E / 35.30707°N 25.5233°E / 35.30707; 25.5233   السكان التعداد السكاني 1003 (إحصاء السكان) (2011)658 (resident population of Greece) (2001)313 (resident population of Greece) (1991)1001 (resident population of Greece) (2021)  الرمز الجغرافي 253770  تعديل مصدري - تعديل  ...

 

 

Sastra India merujuk pada sastra yang dibuat di subkontinen India sebelum 1947 dan di Republik India pada masa setelahnya. Republik India memiliki 22 bahasa resmi. Penghargaan Persekutuan Akademi Sahitya Penghargaan Jnanpith Penghargaan Akademi Sahitya Vyas Samman Saraswati Samman Penghargaan Akademi Paschimbanga Bangla Lihat pula Puisi epik India Sastra India (jurnal) Puisi India Sastra dari India Timur Laut Sekolah Sastra Stephanian Pranala luar Indian Literature on Indohistory Diarsipkan 2...

† Человек прямоходящий Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеНадкласс:ЧетвероногиеКлада:АмниотыКлада:Синапсиды�...

 

 

SLC22A8 المعرفات الأسماء المستعارة SLC22A8, OAT3, solute carrier family 22 member 8 معرفات خارجية الوراثة المندلية البشرية عبر الإنترنت 607581 MGI: MGI:1336187 HomoloGene: 20901 GeneCards: 9376 علم الوجود الجيني الوظيفة الجزيئية • sodium-independent organic anion transmembrane transporter activity• ‏GO:0022891 transmembrane transporter activity• inorganic anion exchanger activity• ن�...

 

 

本條目存在以下問題,請協助改善本條目或在討論頁針對議題發表看法。 此條目需要擴充。 (2013年1月1日)请協助改善这篇條目,更進一步的信息可能會在討論頁或扩充请求中找到。请在擴充條目後將此模板移除。 此條目需要补充更多来源。 (2013年1月1日)请协助補充多方面可靠来源以改善这篇条目,无法查证的内容可能會因為异议提出而被移除。致使用者:请搜索一下条目的...

  关于与「內閣總理大臣」標題相近或相同的条目页,請見「內閣總理大臣 (消歧義)」。 日本國內閣總理大臣內閣總理大臣紋章現任岸田文雄自2021年10月4日在任尊称總理、總理大臣、首相、阁下官邸總理大臣官邸提名者國會全體議員選出任命者天皇任期四年,無連任限制[註 1]設立法源日本國憲法先前职位太政大臣(太政官)首任伊藤博文设立1885年12月22日,...

 

 

Amet-Khan SultanNama asliAmet-Han SultanLahir(1920-10-25)25 Oktober 1920Alupka, Rusia SelatanMeninggal1 Februari 1971(1971-02-01) (umur 50)Moskwa, SFSR Rusia, Uni SovietPengabdian Uni SovietDinas/cabangAngkatan Udara SovietPangkatPodpolkovnikKesatuanResimen Penerbangan Penyerang Garda ke-9Perang/pertempuranPerang Dunia IIPenghargaan PasanganFaina Maksimovna Amet-Khan Sultan (bahasa Rusia: Амет-хан Султан; 25 Oktober 1920 – 1 Februari 1971) adalah seo...

 

 

Culinary traditions of Scotland This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Scottish cuisine – news · newspapers · books · scholar · JSTOR (October 2021) (Learn how and when to remove this message) Haggis, neeps and tatties British cuisine National cuisines English Scottish Welsh Northern Irish Regional ...

This article possibly contains original research. Please improve it by verifying the claims made and adding inline citations. Statements consisting only of original research should be removed. (March 2024) (Learn how and when to remove this message) Branch of Carlism Carlo-francoism (Spanish: carlofranquismo, also carlo-franquismo) was a branch of Carlism which actively engaged in the regime of Francisco Franco. Though mainstream Carlism retained an independent stand, many Carlist militants o...

 

 

Public university in Columbus, Ohio, U.S. This article is about the Columbus campus. For other campuses, see Ohio State University (disambiguation). Not to be confused with Ohio University. Ohio State redirects here. For the U.S state, see Ohio. This article contains academic boosterism which primarily serves to praise or promote the subject and may be a sign of a conflict of interest. Please improve this article by removing peacock terms, weasel words, and other promotional material. (Januar...

 

 

Cultural property register of Switzerland The cover of the 2009 edition of the Inventory, showing the Zytglogge in Bern and the blue shield of the Hague Convention. The Swiss Inventory of Cultural Property of National and Regional Significance (German: Schweizerisches Inventar der Kulturgüter von nationaler und regionaler Bedeutung; French: Inventaire suisse des biens culturels d'importance nationale et régionale; Italian: Inventario dei beni culturali svizzeri d'importanza nazionale e regi...

Helvetii v. Rome, Gallic Wars, 58 BC Battle of BibractePart of the Gallic WarsJulius Caesar and Divico parley after the battle at the Saône. Historic painting of the 19th century by Karl Jauslin.Date58 BCLocationSaône-et-Loire, France46°55′0.001″N 4°1′59.999″E / 46.91666694°N 4.03333306°E / 46.91666694; 4.03333306Result Roman victoryBelligerents Roman Republic Mainly HelvetiiBoiiTulingiRauraciCommanders and leaders Gaius Julius Caesar DivicoStrength Prese...

 

 

Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Cet article ne s'appuie pas, ou pas assez, sur des sources secondaires ou tertiaires (décembre 2022). Pour améliorer la vérifiabilité de l'article ainsi que son intérêt encyclopédique, il est nécessaire, quand des sources primaires sont citées, de les associer à des analyses faites par des sources secondaires. Cet article est une ébauche concernant une compétition de football. Vous pouvez partager vos...

 

 

3rd edition of Miss Grand United Kingdom competition Miss Grand United Kingdom 2023Chloe Ellman-Baker, the winner of the contestDateAugust 13, 2023VenueAures London, LondonEntrants9Placements5DebutsBirminghamDurhamKensington and ChelseaNorth LondonNorwichScotlandSussexWithdrawalsBerkshireKentLeedsLondonManchesterNorth East EnglandWest MidlandsYorkshireAntrimBelfastEdinburghGlasgowBridgendCardiffSwanseaReturnsGreater LondonWinnerChloe Ellman-Baker(Sussex)← 2021 Miss Grand United Kin...

República TogolesaRépublique togolaise  (francés) Estado miembro de la Unión AfricanaBandera Escudo Lema: Travail, Liberté, Patrie(en francés: «Trabajo, Libertad, Patria») Himno: Terre de nos aïeux(en francés: «Tierra de nuestros ancestros») Capital(y ciudad más poblada) Lomé6°07′48″N 1°12′57″E / 6.13, 1.2158333333333 Idiomas oficiales FrancésGentilicio Togolés, -sa[1]​Forma de gobierno República Presidencialista • Pr...

 

 

Philosophical work by Maimonides (c. 1190 CE) This article is about the 12th-century book by Maimonides. For the 1977 book by E.F. Schumacher, see A Guide for the Perplexed. For the 2001 novel by Gilad Atzmon, see A Guide to the Perplexed. The Guide for the Perplexed Maimonides' autograph draft of Dalālat al-ḥā'irīn, written in Standard Arabic with Hebrew script, from the Cairo Genizah[1]AuthorMoses MaimonidesOriginal titleדלאלת אלחאירין‎LanguageJudeo-Arab...