Question about RAII.
Robert.Atkinson at NOSPAM.gmail.com.NOSPAM
Robert.Atkinson at NOSPAM.gmail.com.NOSPAM
Tue Jul 4 07:22:27 PDT 2006
Everyone's already told you that returning an auto-reference is impossible as
the reference gets destroyed by exiting the scope.
Couldn't the compiler detect this and throw an compile-error? From simple
inspection it seems to be a pretty easy addition to the compiler, the syntax is
already quite clear.
In article <Xns97F65C90D676pchapinsovernet at 63.105.9.61>, Peter C. Chapin says...
>
>Hello! I'm a C++ programmer who has started to look at D. I appreciate
>many of D's design decisions. However, I'm a little confused about how
>RAII is supported. It seems like it only semi-works. Consider the
>function below ('Example' is some class):
>
>Example g()
>{
> auto Example object1 = new Example;
> auto Example object2 = new Example;
> Example object3;
>
> if (f()) {
> object3 = object1;
> }
> else {
> object3 = object2;
> }
> return object3;
>}
>
>The idea is that I want to return one of two local objects depending on
>what f() returns. Assume f() interacts with the user so its return value
>can't be known to the compiler. The object that is not returned must be
>cleaned up. Assume that it holds resources other than memory that need
>to be released.
>
>In the example above it looks like both object1 and object2 are
>destroyed and thus the returned reference is invalid. However, if I
>remove 'auto' from the local declarations than object1 and object2 don't
>get destroyed until garbage collection time... which is too late. It
>looks like I'm left with explicitly deleting the object that I don't
>return, but this is manual resource management and not RAII.
>
>To make this example more concrete, suppose the class in question
>represents an on-screen window. Function g() lets the user select one of
>two newly created windows, returning the window selected and removing
>the other from the screen.
>
>Thanks in advance for any comments.
>
>Peter
More information about the Digitalmars-d
mailing list