Talk:Resource acquisition is initialization

message: The C++ Programming Language (Bjarne Stroustrup) (2nd edition) ISBN 0-201-53992-6 : Ch9 "Exception handling" 9.4.1 "Constructors and Destructors" "This technique for managing resources is usually referred to as 'resource acquisition is initialization'. "
This hints at an earlier usage.
51.9.104.223 (talk) 11:44, 20 May 2021 (UTC)
thread_title: Earlier C++ reference

message: Any tips for RAII in Java? Wouter Lievens 12:39, 11 Mar 2005 (UTC)
replies: text: The purpose of a Wikipedia discussion page is to improve the related article, not to provide programming tips. That said, the comment below is correct. -- 71.102.128.42 (talk) 02:32, 17 November 2014 (UTC)

text: I know Java doesn't allow it the way C++ does, that's why I was asking the question :-) Wouter Lievens 19:42, 20 September 2005 (UTC)

text: try-with-resource (and more generally the concept of bracketing / context management) is the common RAII alternative in GC'd language (the other big one being scope / defer-type statements which has similar issues), but strictly inferior because it is unable to handle conditional release without additional structure or a dedicated variant, whereas RAII handles this situation naturally. 178.51.135.179 (talk) 07:56, 5 September 2023 (UTC)
thread_title: RAII in Java

message: What about removing the stub template? I found this article most helpfull.
: Yes, I think it deserves that removal (I'll do it right now) – Adrian | Talk 23:36, 17 November 2005 (UTC)
thread_title:  Remove "stub"? 

message: Who uses RIIA? Googling for "Resource Initialization Is Acquisition" only returns 75 results, most are from mailing lists. DanielKO 00:20, 16 March 2006 (UTC)
replies: text: Agreed, I've never heard it used in that order either. The instances that you can find on Google  are Wikipedia "mirrors" and most likely mistakes otherwise. I'll remove the acronym from the page as per WP:BB for now. -- intgr 11:21, 2 July 2006 (UTC)

text: That was my typo. It's been fixed. Sory about that. —Ben FrantzDale 02:25, 3 July 2006 (UTC)
thread_title:  RIIA? 

message: The C example is looks much more complicated than necessary. What about this, that is much better suited for maintenance:
int c_example() {
    int retval = -1; // assume error
    FILE *f = NULL;
    do {
       f = fopen("logfile.txt", "w+");
       if (f == NULL) {
          retval = -1;
          break;
       }
       if (fputs("hello logfile!", f) == EOF) {
          retval = -2;
          break;
       }
       // continue using the file resource
       retval = 0; // return value 0 is success
    } while (0);
    // Releasing resources (in reverse order)
    if (f != NULL && EOF == fclose(f)) {
        retval = -3;
    }
    return retval;
}
--87.163.200.60 (talk) 11:38, 25 September 2008 (UTC)
replies: text: Often, gotos are seen as evil, since they essentially turn your code into swiss cheese. do { } while (0) also isn't a loop, it's specified explicitly that it is a "breakable block" i.e. you can "break;" out of it in an exceptional case (and even return something from it if you care to use C side-effects). It's commonly macro-ized as STMT(_START/_END), and used from within macros which define blocks of code, because C compilers treat these blocks as a single "statement", hence the name of the macro. Both idioms (goto, stmt) are very popular and equally portable though, so it's really up to the preference of the programmer. The Linux Kernel uses gotos as Linus uses gotos and essentially dictated their use through his BDFL status.  —Preceding unsigned comment added by 76.177.52.225 (talk) 02:14, 29 April 2009 (UTC)
thread_title:  Bad C example 

message: I feel parts of this article contradicts itself.
To me, RAII means resource management through statically predictable
destruction — in C++ by auto variables or std::auto_ptr, or by the
lifetime of some larger object having the resource-owning one as a member.
The part that speaks about std::auto_ptr seems to agree with that definition.
Another part that speaks of "languages that do not support RAII, such as Java"
seems to imply that try ... finally isn't RAII.
A third part states that manually calling a finalize() method in languages
like Java is RAII.
I suppose you can say you use RAII if you consider your resource FOO as owned
by object FOO in general ... but isn't that a more general idea,
a basic tool of any object-oriented programming?
JöG 20:35, 3 September 2006 (UTC)
thread_title:  Is it RAII if it's not automatic? 

message: My first reaction is that this new section is ugly and superfluous.  A simple class wrapper for OpenSocket() and CloseSocket() is just the right thing to do.  In contrast, the scoped_handle<> template obscures the programmer's intention.
My inclination is to remove this section entirely, as it contributes nothing to the concept of RAII and appears to be an exercise in unwarranted cleverness. Xerxesnine 22:27, 31 March 2007 (UTC)
replies: text: Agreed, one example is enough and the new one is rather nonobvious, providing little encyclopedic value. -- intgr 22:36, 31 March 2007 (UTC)
thread_title:  stlsoft::scoped_handle 

message: PHP5 introduces destructors. Does anyone know if they are guaranteed to run in a timely fashion, for example, when a static object passes out of scope? If so, then this technique could be used in PHP5. Either way, the article should mention whether or not the technique is applicable to that language. - Jmabel | Talk 17:37, 21 February 2008 (UTC)
thread_title:  PHP5 

message: GNU C adds a cleanup attribute that helps plain C code in exceptional cases.  —Preceding unsigned comment added by 17.201.20.87 (talk) 19:24, 27 February 2008 (UTC)
thread_title:  GNU C 

message: I believe better wording to replace "the automatic, deterministic destruction" would be "the implicit, synchronous destruction".  I believe "automatic" is not as informative as "implicit" and "deterministic" is not as informative as "synchronous".  In fact, I think "deterministic" can be misleading because the destructor could be implemented with non-deterministic characteristics (such as calling fclose, which does not have a deterministic result).  But I get the impression someone loves the existing wording, since it also shows up in the Java vs. C++ article, so I would like your comments.  --pfunk42 (talk) 05:25, 17 May 2008 (UTC)
thread_title:  "automatic, deterministic" 

message: Googling "mutable RAII" gives 7 hits, many of which are derivatives from this Wikipedia article. "Immutable RAII" fares a little better, giving 171 hits. Some of the hits are for Wikipedia article, some are to discussions where Matthew Wilson, author of the term, is using it. Or to excerpts from Matthew's books. Clearly the term has not caught on, and should not be in Wikipedia. I'll go ahead and remove the mutability section if there's no objection. Matonen (talk) 13:45, 15 April 2009 (UTC)
thread_title:  Mutability section should be removed 

message: Do you guys think the acronym ```SBRM``` (scope-bound resource management) deserves to be included here too? It seems to be more descriptive of what happens here. I can't seem to track down the origin with quick googling though - just various blogs and forums, starting about 2007 and getting more common by 2010. --Cubbi (talk) 18:06, 25 August 2010 (UTC)
thread_title:  SBRM 

message: This article, especially the comparison to other forms of resource management is incomplete without a section that delves into the subject of compositional properties of the different resource management technologies.
The single most compelling property of RAII when compared to try/finally lies in how RAII works with 'deep' resources.
In a pure GC+try/finally world, 'being a resource' is transitive when used in composition. In a RAII world it isn't.
If in a GC+try/finally world an object contains a 'deep' resource, than this object requires manual resource management at the level of the user of the composite object. With RAII the resource (and thus the resource management) is fully captured at the deeper levels of composition and neither the higher levels of composition nor the user of the composite object are exposed to the fact that the there is a deep resource in there. That is, RAII provides the possibility of encapsulation of resources, while for the alternative, composition will brake encapsulation. 
One thing that aggravates the problem for alternative resource management technologies (GC+try/finally) is polymorphism. Combined with polymorphism, not only 'holding' a deep resource makes a composed object require manual resource management, but also composition using any polymorphic component will turn a composite object into an object needing manual resource management. As RAII doesn't have the encapsulation problems it also does not have the polymorphism problems that GC+try/finaly has.  —Preceding unsigned comment added by Pibara (talk • contribs) 09:22, 11 May 2011 (UTC)
replies: text: A problem with the added section is that it looks like your own research/analysis. Being an encyclopedia, WP does not publish original thought - all content should be sourced to reliable references. This article already has problems in this respect. Regards, decltype (talk) 10:17, 5 July 2011 (UTC)
thread_title:  Resource management & composition. 

message: The article seems to assume that RAII is only about scope-based automatic construction and destruction of objects. It omits an extremely important part of RAII, namely copying and assignment (which in C++ is implemented in the form of copy constructors and copy assignment operators). This is quite obvious as the article gives as examples of "RAII" the gcc extension "cleanup" and the Java "finally" block. That's only part of RAII. Those do not handle copying and assignment properly.
Copy semantics is what allows, for example, returning objects from functions by value, giving objects as value-based function parameters, copying objects (obviously), creating entire arrays of objects (each element being default-initialized or initialized as a copy of an existing object) and so on, while still fully adhering to the RAII mechanism. This is most certainly not covered by "finally" blocks or a "cleanup" attribute.
Another aspect that's missing is that RAII works in C++ even on the heap: As long as the container structure is allocated and deallocated properly, the contained objects will follow the RAII rules appropriately. (This is the reason why, for example, the standard library data structures do not need to know how their elements are copied and moved around, as RAII takes care of that.)
Comparing RAII to Java's "finally" blocks is, at the very least, misleading.  — Preceding unsigned comment added by 84.249.92.156 (talk) 06:25, 12 April 2012 (UTC)
thread_title:  Copying and assignment 

message: The article seems to imply that there is no RAII in C#, but this is not true: it merely works in a different way, with more explicit syntax, as already described in this talk page (see C# example above).
This has nothing to do with C# not having deterministic memory deallocation, as RAII is not fundamentally about memory allocation. For example, this C# example is RAII, since reader and writer objects are automatically disposed (i.e. closed) upon exit from the using scope. 212.92.211.195 (talk) 14:32, 30 January 2013 (UTC)
replies: text: The article clearly mentions the dispose pattern as an alternative for languages without determinstic memory deallocation. The dispose pattern serves as a good alternative to RAII in many situations, but it can only be used for shallow resources within a method. One e.g. still have to explicitly implement the Dispose method and manually close all resources belonging to a class when developing own classes in C#. This is not the case for C++ with RAII. --Fredrik Orderud (talk) 16:03, 30 January 2013 (UTC)

text: C# does not have RAII for expression lifetime objects or for state lifetime.  It did not have scope-based until the using clause was added, and this failed to actually add full RAII because it did not address the other cases.  C# does not automatically cleanup resources contained by other resources.  Additionally, the object dtor will still be accessed after the dispose, and this multistage cleanup leaks referentiality and, if the advice given by MSDN on proper dispose/dtor use is followed, requires increased complexity.  There are a number of ways in which the C# using (and Java try-with-resources) does not provide the complete automation and referentiality assurances that RAII as a concept intended.  It is true, though, that C# has deterministic scope cleanup, but that is discussed elsewhere on Wikipedia.  Ex0du5 5utu7e (talk) 22:35, 3 December 2014 (UTC)
thread_title:  RAII in C# 

message: Through 2012 September, The RAII entry spent more text on usefully showing the bonding together of creating a data object and acquiring auxiliary resources, and showing how falling out of scope could release those auxiliary resources.  It had examples in C++, Java, Ruby, Python, and Smalltalk which all essentially showed RAII support (despite the section being conflictingly titled "Resource Management without RAII"), using library calls and closure blocks which all essentially show that the languages can trigger the destructor when needed.
The fact that the first mentioned use for RAII in the article was given as mutex locks is fairly esoteric for some programmers, but the C++ example does show two implicit examples of RAII through C++ features, one for the mutex and one for the file.
The "GCC extensions for C" subsection, about autodeallocation, which is related to RAII despite being in the wrong section, only covers deallocation on falling out of scope.  Although useful, it would be more edifying in a complete example showing the allocation part as well, as the old, long C example did (up to 2012 September or so) with the RAII macro automatically calling the destructor for the C object at the end of the scope.  Extract:
#define RAII(t, v, a,...) \
    for(int _outer_once = 1, _inner_once = 1, _jumped = 0 ; _outer_once-- ; \
        _jumped && (Throw(_jumped), 1), 1)                              \
        for(_jumped = setjmp(_jmp_bufs[_jmp_i++]) ; _inner_once-- ; )   \
            for( t *v = t ## New(a, __VA_ARGS__) ; v ; t ## Delete(&v))
[...]
    RAII(File, from, "file-from", "r+") { /* r+ to ban opening dirs */
         RAII(File, to, "file-to", "w") {
             int c;
             while(EOF != (c = FileGetc(from)))
                 FilePutc(to, c);
             puts("copy complete");
         }
    }
Note that although that code does use variadic macros and some recent standardized C features, it's not strictly confined to GCC, whereas the RAII_VARIABLE macros appears to be far less portable.
That "Ad-hoc mechanisms" section was in one key way one of the most interesting (alert: I'm biased, I wrote it, and I agree shorter would be nice, but it's not easy to accomplish) because instead of just using a language feature that implements key RAII components implicitly, it instead had to *explicitly* show how the initialization was part of the declaration, and how the destructor was called even in the face of errors.
Renaming that section from "Ad-hoc mechanisms" to "Implementing RAII in non-RAII Languages" would really have been a more reasonable choice than simply claiming "ad-hoc work-arounds are in general of little encyclopedic value" and tossing it.  
Further, it also addressed a lot of the tradeoffs involved in retrofitting RAII to languages without direct support, the benefits achieved with RAII, and so on.  That part of the article is still available in its original form at http://www.talisman.org/~erlkonig/documents/ad-hoc-exceptions-in-c/
(Aside; the the second C example was inferior, essentially being an example of a way to avoid having deeply-nested blocks to handle failures.  While common in kernel code, it was not RAII - the uninitialized FILE pointers and reliance on specific resource-release calls have nothing to do with RAII.  Dropping that one made sense.)
So I'm not very happy with what's left of the RAII entry, but order to work around what bias I might have, I'd like to leave it up others going forward.
C. Alex. North-Keys (talk) 21:52, 5 August 2013 (UTC)
thread_title:  RAII article in mid 2013 less useful than in mid 2012. 

message: In the sentence "In RAII, holding a resource is tied to object lifetime: resource allocation (acquisition) is done during object creation...", should the colon after "lifetime" be a period or a semicolon?  — Preceding unsigned comment added by 188.126.200.132 (talk) 19:31, 11 July 2014 (UTC)
thread_title:  object lifetime: resource allocation 

message: The line 
"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."
is incorrect as written because of the "stack-based" modifier. It could be made "more correct" by simply removing the modifier, but it still misses the point because it is not just "dynamically allocated objects" that can be managed, and you typically do not want dynamic allocation unless you are explicitly not stack-based.  The only time you use dynamic allocation with scope lifetime is when you need more memory than the stack can allow or need special memory permissions, both fairly rare.
When you have an interface that can receive asynchronous events, though, and you need something to have a lifetime that lasts longer than the first event scope, that's when you typically need dynamic allocation.  This is what State Machines were created for.  State Machines are RAII for asynchronous events.  A State is what manages the automated lifetime between the two events.  Everything the State holds (everything contained in the object) is automatically created when the State is created and destroyed when the State is destroyed.  This solves exactly the same problems that scope based RAII solves:
* Name referentiality matches lifetime.  There are no zombie objects (objects that aren't fully "live" but aren't completely "dead" and unreachable either) or multi-stage construction or destruction.  If you can reference the name of the object (within the State in the Machine pattern, or within the scope in the traditional), then it is fully usable.
* Automation of management and cleanup.  There is no possibility of mismatch between create and destroy code, where resources leak creates or double destroy.  When you add the ownership relation, the cleanup is inserted by the compiler.  You only need one expression, not two, to declare the lifetime intent, so divergence is not possible.
In fact, there are actually four lifetimes, all of which are managed by RAII:
# Expression lifetime - anonymous objects created during the evaluation of an expression are automatically cleaned up at the end of the expression evaluation.  This is used extensively in proxy objects, stream formatters, expression templates, and numerous other common idioms of RAII languages.  You will note that the controversial languages that do not inherently support RAII but support "similar mechanisms" (like C# or Java) do not support this in an automated fashion, which is one reason there is controversy with such labelling.
# Scope lifetime - what the article mostly discusses.
# State lifetime - mentioned above, between asynchronous events.
# Application lifetime (or, better, translation unit lifetime) - file scope objects that are created by the language rules for file-scope objects and destroyed on program exit (in the atexit cleanup, for instance, in c++).
In all these cases, referentiality equals lifetime and management is automated by the simple declaration.  That is RAII, and a good article should mention these things.  Ex0du5 5utu7e (talk) 22:23, 3 December 2014 (UTC)
thread_title:  Non-stack-based RAII (asynchronous event RAII and other) 

message: Perhaps I'm missing something, but there appears to be a serious error in the C++ coding sample: the destructor of the static mutex instance will not be called until the program exits. The static variable may not be visible outside the scope of the function in which it resides, but it is nevertheless global. So if we rely on the destructor to unlock the code, then the mutex will remain locked after the first call.
It looks to me that to make this function work would remove most of the RAII characteristics that it is trying to demonstrate.
Maybe a better example of RAII would be a function that returns an instance of an object?  I.e., the called method allocates the instance on the stack,  automatically copies the instance to the return value, which is deleted when it goes out of scope in the calling routine.
Rstinejr (talk) 13:39, 29 December 2014 (UTC)
thread_title:  Error in C++ example 

message: Does anyone have WP:V sources that can confirm this? Ushkin N (talk) 17:26, 30 May 2016 (UTC)
replies: text: There is  – Tea2min (talk) 06:23, 31 May 2016 (UTC)
replies: text: If it is a programming idiom, why is it enlistet as a software design pattern? (At a higher level there are architectural patterns, and below software design patterns, there are idioms.)--Sae1962 (talk) 16:05, 28 November 2016 (UTC)
thread_title:  Is it a [[Programming idiom]]? 

message: I haven't found the cppcon talk calling it DRES (Destruct Resources on Exit Scope) yet but here is one reference in the meantime: C++ mingw g++ and Notepad++  — Preceding unsigned comment added by JeffyTheDragonSlayer (talk • contribs) 09:07, 9 January 2020 (UTC)
replies: text: Indeed. And when searching the interwebs for "Destruct Resources on Exit Scope" the only other source I found was CppCon 2017: John D. Woolverton "C Pointers", referencing the video and DRES is indeed mentioned at 2:34, and even here the abbrevation is explained. Hm. Not sure if that means it's a "common other name" though. -- Evilninja (talk) 09:24, 9 January 2020 (UTC)
thread_title:  Other names for this idiom