Add your own alternative version
Stats
270.7K views 713 downloads 70 bookmarked
Posted
17 Apr 2005
|
Comments and Discussions
|
|
I have finally understood RAII concept in examples. Thank you.
|
|
|
|
|
"Le Chaud Lapin" coined a new and IMO much better name for RAII: Yin/Yang[^]. "Yin/Yang symbolizes duality and symmetry. For every action, there is an opposite reaction."
I’d add that dynamically created objects may be created in any member function (not just the constructor) and may be deleted in any member function, preferably and at least in the destructor. This is also illustrated in the above article.

|
|
|
|
|
Tom Cargill's seminal article 'Managing Dynamic Objects in C++'[^] (DDJ Jul 22 2001) is available online. It describes, among others, the 'Creator as Sole Owner' pattern on which RAIIFactory is based.
|
|
|
|
|
Another interesting article by Danny Kalev: "A Garbage Collector for C++"[^]
<quote>
"If garbage collection is almost 50 years old, one wonders why many programming languages have deliberately chosen not to support it. The answer, as usual, is that a GC is no silver bullet."
|
|
|
|
|
"The main “Smart pointer” is a reference counted pointer, shared_ptr, intended for code where shared ownership is needed. When the last shared_ptr to an object is destroyed, the object pointed to is deleted. Smart pointers are popular, but should be approached with care. They are not the panacea that they are sometimes presented to be. In particular, they are far more expensive to use than ordinary pointers, destructors for objects “owned” by a set of shared_ptrs will run at unpredictable times, and if a lot of objects are deleted at once because the last shared_ptr to them is deleted you can incur “garbage collection delays” exactly as if you were running a general collector. The costs primarily relate to free store allocation of use count objects and especially to locking during access to the use counts in threaded systems. Do not simply replace all your ordinary pointers with smart_ptrs if you are concerned with performance or predictability. These concerns kept smart_ptrs “ancestor”, counted_ptr, out of the 1998 standard. If it is garbage collection you want, you might be better off simply using one of the available garbage collectors (http://www.research.att.com/~bs/C++.html)."
Stroustrup: C++ in 2005[^]
|
|
|
|
|
First of all, I think your concept of an RAII factory is useful for certain situations, but is really nothing more than a very simplistic pooling mechanism with creation symantics. At least to me, it seems like the concept complicates the vast majority of situations I can think of. Straight-up RAII, by which I mean, MyClass allocates and de-allocates it's own resourcesand is constructuted within a stack-frame is usually suffecient for most situations.
Your method is only really useful when a particular function (stack frame) is going to allocate multiple (many) instances of a class and then pass that down through function class/etc. The problem here is that the initial function should be responsible for allocating MyClass instances unless naming those instances as variables is unnecessary (it just needs an array/list/stack/etc. of them as nameless objects). For this case, a typical collection (std:list, etc) will probably satisfy the need and will also provide RAII for the objects it contains (MyClass) which provide RAII for themselves.
For those situations where objects must be completely handled as pointers, auto_ptr is often enough, but if a programmer wants more, he/she can easily write a wrapper class to completely hide the underlying object construction. From my perspective, what your concept lacks to be more useful is a reference counting mechanism; which makes it something entirely different from what you are trying to accomplish.
Ultimately, C++ is meant to be a highly flexible language that allows programmers to create useful/powerful/creative solutions. It's power lies in the fact that I can choose to use GC, RAII, RAII Factories, pools, smart pointers, auto_ptr, wrapper classes, or just plain new/delete when I need it and how I see fit. None of these are panaceas and none fit all or even most situations. They are tools in an ever increasing toolbox that allow programmers to choose when/where to deal with complexity.
C++'s real problem is that it is a victim of it's own success. It is too powerful and too flexible. It is easy to do things a bad way, especially if you do not know what the right way is. Software development is partly shifting from an art to a practice. C++ is a wonderful pallete for an artist, but .NET/Java are better for practicioner programmers. Which is exactly why C++ is going to continue to be an important language for some time to come.
Sorry for the rant. I did enjoy your article and I think it is a good tool for situations where appropriate.
|
|
|
|
|
Matt Gullett wrote:
Your method is only really useful when a particular function (stack frame) is going to allocate multiple (many) instances of a class and then pass that down through function class/etc. The problem here is that the initial function should be responsible for allocating MyClass instances unless naming those instances as variables is unnecessary (it just needs an array/list/stack/etc. of them as nameless objects). For this case, a typical collection (std:list, etc) will probably satisfy the need and will also provide RAII for the objects it contains (MyClass) which provide RAII for themselves.
std::list is designed only for value type objects. For (Non-copyable) 'entity objects' (called 'reference objects' in C#) RAII Factory is a mechanism that consistently and reliably takes care of resource management. And it makes you consider the scope of a resource.
Matt Gullett wrote:
C++'s real problem is that it is a victim of it's own success. It is too powerful and too flexible. It is easy to do things a bad way, especially if you do not know what the right way is. Software development is partly shifting from an art to a practice. C++ is a wonderful pallete for an artist, but .NET/Java are better for practicioner programmers. Which is exactly why C++ is going to continue to be an important language for some time to come.
I agree with your point of view. Unfortunately there seems to be no attempt to simplify the use of C++. Quite the contrary (see e.g. C++/CLI, Boost, ...)!
|
|
|
|
|
|
emilio_grv[^] has just published an article[^] about 'reference counting smart pointers and handles of various flavours'. You can directly compare the RAII factory to the smart pointer approach with respect to capability and usability.
|
|
|
|
|
One of the bonuses you get from this approach is more flexibility in exactly _how_ you do your memory management. For example, you're perfectly set up to use memory pools (eg boost::pool) to eliminate most of the memory management overhead. I think this is a significant benefit which is worth mentioning in the article.
Something that has never been clear to me, though, is how you can use RAII when you have a container with a highly variable (sometimes decreasing) number of elements. Sure, you know the scope of the container, but you can't always wait around until the container is destroyed before releasing all the objects. Moreover, the objects themselves may have internal RAII objects inside them which need to have their destructors called.
Any thoughts on this?
|
|
|
|
|
Don Clugston wrote:
One of the bonuses you get from this approach is more flexibility in exactly _how_ you do your memory management. For example, you're perfectly set up to use memory pools (eg boost::pool) to eliminate most of the memory management overhead. I think this is a significant benefit which is worth mentioning in the article.
Good point! Actually one of the boost::pool templates is similar to the generic RAIIFActory (GFactory) presented above. The scope bound approach also bears some resemblance with obstacks in C on Unix.
Something that has never been clear to me, though, is how you can use RAII when you have a container with a highly variable (sometimes decreasing) number of elements. Sure, you know the scope of the container, but you can't always wait around until the container is destroyed before releasing all the objects. Moreover, the objects themselves may have internal RAII objects inside them which need to have their destructors called. Any thoughts on this?
The RAIIFactory defines the maximum lifetime of created objects. I mention in the article that objects may be destroyed earlier (see 'Disposing Objects'). Albeit the user must ensure that the pointer to the disposed object will not be used any more. The factory implementation should probably be changed from vector to hash table when objects are disposed frequently. Also, for heavy create/dispose scenarios memory pools (as you mention above) are ideal, even 'local' pools where each factory object manages the raw memory of its created objects. In gerneral, RAIIFactories can also handle shorter actual lifetimes of objects.
There are settings where a RAIIFActory is not appropriate. One can be described as Publisher-Subscriber-Pattern (a.k.a. Observer). Subscribers get a reference to a resource from the publisher (the 'factory') but never give it back. They just discontinue to use it sometime without giving notice to the publisher. In this cases one should look for other solutions.
|
|
|
|
|
RAII is an excellent and extremely useful programming idiom and I'm using it ALL the time. However, I don't see any need for such a RAII factory, at all.
worndown
|
|
|
|
|
worndown wrote:
Re: Did Stroustroup mention RAII factories?...
No, Stroustrup did not mention RAII factories. I'll update the article to prevent any misunderstanding.
RAII is an excellent and extremely useful programming idiom and I'm using it ALL the time. However, I don't see any need for such a RAII factory, at all.
Stroustrup said: "For example, a container is a systematic way of dealing with objects. .... The name of the game here is to get allocation out of the way so you don't see it. If you don't directly allocate something, you don't directly deallocate it, because whoever owns it deals with it. The notion of ownership is central."
RAII factory is a container that creates and owns objects so that the user needs not directly allocate and deallocate anything. That's the gist.
|
|
|
|
|
You article begins with the right stuff:
void myFun()
{
XyzLib::Mutex mutex;
mutex.lock()
// do things in series ...
}
// mutex.unlock() is automatically called in the destructor of mutex
This is perfect example of RAII and you should not go beyond this point. If you want to allocate resources inside Mutex dynamically, do it, nothing prevents you from that and you don't have to invent RAII factory, which only adds unnecessary inderection, complexity and confusion, when objects are allocated and destroyed at different scopes as in you example:
void myFun (int n)
{
MyClassFactory factory;
for (int i = 0; i < n; ++i)
{
MyClass* p = factory.create (i);
// ...
}
}
// all objects created by factory are deleted here!
RAII stands for 'Resource Acquisition Is Initialization'. I think that the code above contadicts this idiom.
Look into source/sink approach.
worndown
|
|
|
|
|
Yes, all objects created by 'factory' will be destroyed upon exiting 'myFun', but you're going to have a bunch of dangling pointers if care weren't taken to nullify them prior to exiting the function, because 'MyClass::p' will be pointing to object(s) that no longer exist.
OTOH, RAII seeks to remove that concern altogether, because what you don't allocate, you don't have to deallocate.
William
Fortes in fide et opere!
|
|
|
|
|
Actually Stroustroup invented RAII.
From wikipedia:
Resource Acquisition Is Initialization, often referred to by the acronym RAII, is a popular design pattern in several object oriented programming languages like C++, D and Ada. The technique, invented by Bjarne Stroustrup[1], ensures that when resources are acquired they are properly released by tying them to the lifespan of suitable objects: resources are acquired during the initialization of objects, when there is no chance of using them before the resource is available, and released with the destruction of the same objects, which is guaranteed to take place even in case of errors.
|
|
|
|
|
I voted this article 2 becase i think it obfuscated developers.
What the difference between RAII factory and smartptr?
RAII factory caontains many pointers smart ptr contains one(common cases)
RAII factory have fixed method of creation & destruction of all contained objects, smartptr incapsulates only destruction (which can be template policy)
RAII factory have fixed objects lifetime, smartptr can be destroyed anytime and lifetime can be increased.
I think RAII factory like a container of smart-pointer with constrains. Resolving any of this constrains will be step back to smart-pointers.
RAII factory have much unmotivated restrictions for object manipulation.
example - sometimes i create chain of 2-3 smart-pointers
lowest level is creates\destroys real object
top level prevents MT-access.
i don't think this possible for RAII-factory
|
|
|
|
|
rm822 wrote:
I voted this article 2 becase i think it obfuscated developers.
What the difference between RAII factory and smartptr?
RAII factory caontains many pointers smart ptr contains one(common cases)
RAII factory have fixed method of creation & destruction of all contained objects, smartptr incapsulates only destruction (which can be template policy)
That's an important difference. If you want that "allocation and deallocation disappear from the surface level of your code" then smart pointers are not an appropriate tool.
RAII factory have fixed objects lifetime, smartptr can be destroyed anytime and lifetime can be increased.
Again, a crucial discrepancy. It's the difference between deterministic and non-deterministic resource management.
I think RAII factory like a container of smart-pointer with constrains. Resolving any of this constrains will be step back to smart-pointers.
RAII factory have much unmotivated restrictions for object manipulation.
The only restriction is that the RAII factory and the created objects use 'scope based' resource management. IMO, that's a feature, not a liability.
example - sometimes i create chain of 2-3 smart-pointers
lowest level is creates\destroys real object
top level prevents MT-access.
i don't think this possible for RAII-factory
I don't see why not. Actually, real pointers created by a RAII factory are much more flexible than 'smart pointers'. You can just use them everywhere a pointer is required (sounds strange, but real pointers can be uses as pointers ).
|
|
|
|
|
Very good article (in a way, you have closed a missing point on CP). However, I just have to disagree on Smart Pointers, and partially GC.
In a way, Smart Pointers provide deterministic destruction* where classic RAII fails due to C++ scoping rules: RAII is such a wonderful "fire and forget" mechanim, because you can bind the lifetime of an object X to either a C++ scope, or to one other object.
This mechanism fails, however, if you need binding across multiple objects or scopes. Smart Pointers cover probably 80% of these scenarios naturally.
This also explains why they have to have pointer semantics: You need to access one object X from different scopes, for which you normally need pointers. So they recycle a known concept (dereferencing), to provide the same feature (access to a shared object from multiple locations)
Smart Pointers in C++ have a kind of neglected history, I see two reasons for that:
First, stl included auto_ptr only, the most hideous, complex, and least applicable of resource managing smart pointers.
Second, Pointers are an almost atomic concept (in the sense that native pointers are very small, and most operations on them take a single clock cycle). Smart pointers can model this only partially, therefore they have to make various tradeoffs, so there is no single "perfect" implementation possible.
*)I fully agree that this is the core benefit of "C++ - RAII", even though I think Stroustrup did intend it in a different way.
Pandoras Gift #44: Hope. The one that keeps you on suffering. aber.. "Wie gesagt, der Scheiss is' Therapie" boost your code || Fold With Us! || sighist | doxygen
|
|
|
|
|
peterchen wrote:
In a way, Smart Pointers provide deterministic destruction* where classic RAII fails due to C++ scoping rules: RAII is such a wonderful "fire and forget" mechanim, because you can bind the lifetime of an object X to either a C++ scope, or to one other object.
If you return a resource from a function by smart pointer the release of the resource is not deterministic any more. The function has ended but the resource release is pending. Yes, the resource release is smoehow assured by the smart pointer, but non-deterministic.
This mechanism fails, however, if you need binding across multiple objects or scopes. Smart Pointers cover probably 80% of these scenarios naturally.
This also explains why they have to have pointer semantics: You need to access one object X from different scopes, for which you normally need pointers. So they recycle a known concept (dereferencing), to provide the same feature (access to a shared object from multiple locations)
If you use an object in many scopes you create dependencies to that object in these scopes anyway. You can create the object on the stack in the 'highest' scope and pass it to 'lower' functions without the need for a smart pointer.
Smart Pointers in C++ have a kind of neglected history, I see two reasons for that:
First, stl included auto_ptr only, the most hideous, complex, and least applicable of resource managing smart pointers.
IMO, auto_ptr is the best of the obnoxious resource managing smart pointers because it does not allocate a mostly superfluous counter object.
BTW, following are some cornerstones of the 'smart pointer waves' in the last 15 years (from my point of view):
- Daniel R. Edelson published "Smart Pointers: They're Smart, but They're Not Pointers", http://www-sor.inria.fr/publi/SPC++_usenixC++92.html[^]
- Scott Meyers analyzed smart pointers in his book and in several articles, http://www.aristeia.com/publications_frames.html[^]
- auto_ptr was introduced into the C++ Standard and acclaimed, http://www.gotw.ca/publications/using_auto_ptr_effectively.htm[^]
- smart pointers were boosted to new dimensions by boost::smart_ptr without solving the old problems, http://www.boost.org/libs/smart_ptr/smart_ptr.htm[^]
|
|
|
|
|
Roland Pibinger wrote:
If you return a resource from a function by smart pointer the release of the resource is not deterministic any more. The function has ended but the resource release is pending. Yes, the resource release is smoehow assured by the smart pointer, but non-deterministic.
First, what means "deterministic" to you?
To me, the important point is: the moment ofdestrucion depends only on the use of the very object itself, not on other factors.
Second, how do you return a managed resource from a function, if it does not yield a copy constructor?
Roland Pibinger wrote:
You can create the object on the stack in the 'highest' scope and pass it to 'lower' functions without the need for a smart pointer.
Umm... wouldn't this mean pushing the data to the outermost scope, i.e. making it global? This is at least impractical for scarce resurces, and hinders isolation of concerns.
Smart pointers are not panacea. But neither is scope-based RAII. Nor GC. I expect a good C++ developer to use RAII automatically, use smart pointers where they make sense, and be hesitant of GC in a C-based environment.
What are your problems with reference counting smart pointers?
Pandoras Gift #44: Hope. The one that keeps you on suffering. aber.. "Wie gesagt, der Scheiss is' Therapie" boost your code || Fold With Us! || sighist | doxygen
|
|
|
|
|
peterchen wrote:
First, what means "deterministic" to you?
To me, the important point is: the moment of destrucion depends only on the use of the very object itself, not on other factors.
'Deterministic' refers to the lifetime of a resurce in a unit of code, typically a function. Example:
auto_ptr<MyClass> foo();
In this case the lifetime of the returned MyClass object is not determined by foo() . By looking at foo() you don't know when the returned object is destroyed. But in
void foo2();
all resources are deterministically released at the end of foo2 (disregarding global variables and programmer errors). This concept is akin to the commit/rollback semantics known from databases.
Second, how do you return a managed resource from a function, if it does not yield a copy constructor?
I avoid it. I see functions as 'services' that do something for me and report success or error afterwards but don't bother me with resources.
Roland Pibinger wrote:
You can create the object on the stack in the 'highest' scope and pass it to 'lower' functions without the need for a smart pointer.
Umm... wouldn't this mean pushing the data to the outermost scope, i.e. making it global? This is at least impractical for scarce resurces, and hinders isolation of concerns.
... the outermost scope in which they are actually used.
What are your problems with reference counting smart pointers?
None, because I don't use them. (in general, the same as for auto_ptr plus the unnecessary dynamically allocated counter object in each r.c.s.p.)
|
|
|
|
|
Roland Pibinger wrote:
- What are your problems with reference counting smart pointers?
None, because I don't use them. (in general, the same as for auto_ptr plus the unnecessary dynamically allocated counter object in each r.c.s.p.)
Well, I think there's too much religion and very few science in this kind of answers:
I don't pretend to offend anyone, but is a matter of fact that –even if all catholic Popes still disagree about the use of condoms and of sex outside marriage- the most of self-saying "catholic people" use them and have sex before marriage.
The metaphor is to say only one concept: whatever "right" can be a thing you would like to be, that "thing" will always go its own way, with a "best compromise" logic, when applied on a wide population. You can "influence it", not change it in its nature.
But programming should be a science, not a religion.
Smart pointers everywhere is wrong as RAII everywhere is wrong.
The good programmer choose the –case by case- the pattern that best fits please note the program needs (not his own needs). Object lifetime is not always something you can decide aprioristically. And "determinism" is not the concept you mention (well … not in the official mathematical sense). Destruction by reference counting is deterministic as destruction in scope. (Smart pointers are destroyed by scope, after all…) GC isn't because the destruction action is not taken as direct consequence of a program action.
To say "I don't have problem because I don't use it" describing another pattern as a replacement for that, doesn't make a good impression. There's nothing scientifically meaningful in that.
I use reference counting widely without any particular problem. As I use RAII. I'm diffident of GC in C++ program, not because I'm diffident on GC, but because I don't see (unlike for RAII and smart pointer) any binding with any C++ native scoping mechanism.
2 bugs found.
> recompile ...
65534 bugs found.
|
|
|
|
|
emilio_grv wrote:
Roland Pibinger wrote:
What are your problems with reference counting smart pointers?
None, because I don't use them. (in general, the same as for auto_ptr plus the unnecessary dynamically allocated counter object in each r.c.s.p.)
Well, I think there's too much religion and very few science in this kind of answers ..
Smart pointers everywhere is wrong as RAII everywhere is wrong.
As I said before, RAII can hardly be overused (at least I don't see how).
The good programmer choose the –case by case- the pattern that best fits please note the program needs (not his own needs). Object lifetime is not always something you can decide aprioristically.
You start case by case and gradually develop towards styles, idioms, patterns. A library, e.g., must conform to a certain 'philosophy' to be usable. The little sister of KISS is KIU (Keep It Uniform ).
And "determinism" is not the concept you mention (well … not in the official mathematical sense). Destruction by reference counting is deterministic as destruction in scope. (Smart pointers are destroyed by scope, after all…)
If you return a smart pointer to a resource that may be returned again then you can hardly call this 'deterministic'. The usage of 'deterministic' here is close to the ACID properties of database transactions (see also link to Herb Sutters article above).
To say "I don't have problem because I don't use it" describing another pattern as a replacement for that, doesn't make a good impression. There's nothing scientifically meaningful in that.
I don't use resource-owning smart pointers because they mix two unrelated concepts: (de-)referencing and resource-handling. Besides that, 'smart pointers' are not pointers, i.e. they cannot provide the full syntax of pointers.
I use reference counting widely without any particular problem.
IMO, reference-counting works well when it's an implementation detail, invisible to the user (when r.c. is encapsulted).
|
|
|
|
|
You're still climbing glasses, my friend!
Many acronym and citation... and no samples by you!
Let me do a counter example: consider an application that lets a user editing a document by placing, moving and removing a variety of objects (in human-language common sense). Think to MS PowerPoint, for example.
The fact that the user has a "delete" command in a menu, doesn’t make you able to "destroy by scope". The scope in which the objects live is the document. If you destroy the document you destroy the objects. Right: RAII factory works.
But what about a "delete" command? You can remove the objects –oops! The object pointers- from the objects collection that represent the document [1], but the objects will be still there until the document will be closed.
Now, think a user inserting 10 thousand object, "deleting" them, inserting other 10 thousand ... three four five ... one hundred times. When do you'll ever eliminate the "deleted" 100thousand objects?
Are you going to fill-up the entire memory with things the users will no more access anyway?
Now, consider a reference counting pointer with casting capability inside a collection, and all object sharing a same common base. The user choose "delete", and you remove the "pointer" from the collection representing the document. Full stop. The object will continue to exist only if it is also referred from inside another collection (for example an "undo" list) and will be deleted when no more needed[2].
You can think this is ugly, you can find as many people you want that agree. Burt you cannot say this doesn't work, or that it "has problems"! That fact that many people agree on something doesn't make that something "true". Fore a science things are "true" when replicate coherently, independently on "opinions". "Good" and "Bad" .. it is another story.
If this "have problems" tell me "what are the problems". I don't see any. May be I'm wrong, but you did nothing to explain me. You simple say "I feel this's wrong".
But saying "I don't use so I don't have problem ..." is like saying by definitiomn "true = good / false = bad". That's not a definition. It's a prejudice.
[1] Please note that such a collection must have a polymorphic content: hence forget about the STL "value semantic": pointers and virtual function, in these cases, are a must. Inheritace of template parameter (that is: policy design of the objects) doesn't help a lot.
[2] This is still "determinism" since "when no more needed" is a well defined and predictable event. The fact that someone use this name in more strict definition, doesn't change the nature of things. "Deterministic" is a legitimate Englis dictionary term. And the fact that someone use acronyms to give a "hidden name" to this misinterpretation of words, doesn't change the physics, nor the language. It is not "when someone will be interested in looking if no more needed", like in GC. That's non-determinism.
Again: you can think this is "hugly", but you cannot say "it's wrong".
2 bugs found.
> recompile ...
65534 bugs found.
|
|
|
|
|
|
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
|