Question about RAII.
Oskar Linde
oskar.lindeREM at OVEgmail.com
Tue Jul 4 06:31:22 PDT 2006
Peter C. Chapin skrev:
> 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;
> }
It looks like you want some kind of transfer semantics. You can do that
manually:
if (f()) {
object3 = object1;
object1 = null;
}
else {
object3 = object2;
object2 = null;
}
D lacks the necessary(*) provisions that would be needed to implement
such behavior automatically. (like the c++ auto_ptr)
> 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.
The both raii variables have no way of knowing if other live references
to the same object exists. They are not cleared when assigned to any
other reference holding variable or passed to functions etc.
/Oskar
*) The obvious implementations would be a pointer wrapping struct, but
for this D lacks:
- assignment operator (and possibly copy) overloading for structs
- destructors for structs
More information about the Digitalmars-d
mailing list