Question about RAII.

Peter C. Chapin pchapin at sover.net
Tue Jul 4 06:05:58 PDT 2006


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