Question about RAII.

Chris Nicholson-Sauls ibisbasenji at gmail.com
Tue Jul 4 06:18:55 PDT 2006


Peter C. Chapin wrote:
> 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

An auto referance such as those above is guaranteed to be destroyed at the end of the 
scope in which it is declared.  Returning such a referance is a no-no, as the object on 
the other side no longer exists when the function has ended!  (If you had directly 
returned object1 or object2, you should have gotten a compile-time error I believe.)

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list