Notes on Defective C++

Jim Hewes jimhewes at gmail.com
Sat Dec 13 16:13:11 PST 2008


"Christopher Wright" <dhasenan at gmail.com> wrote in message 
news:ghlntc$ku3$1 at digitalmars.com...
> In this case, File should close itself in its destructor. Class A can't 
> close its file in its destructor because the file might have already been 
> collected and finalized. And you can't use a scope guard in this case 
> because A doesn't let you just close the file.
>
> I'd say that, if File doesn't close itself in its destructor, that's an 
> error. If File has this error, A should offer a way to close the file 
> without side effects.

Well, File can clean up after itself in its own destructor, but the problem 
is you don't know when that will happen. This might be less of a problem 
with a file if you're not going to use that file again. But it might be more 
of a problem for things like mutexes that you want to be released right 
away.
The solution in C# is that the class must provide a Dispose function. But 
then any owning class must remember to also provide a Dispose function and 
dispose of the disposable objects it owns. If you need to remember this, it 
becomes a source of possible error. It you've looked at the code 
(http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) 
it's a bunch of extra stuff you need to do. It's kind of like going back to 
the C++ way of using new/delete for memory, having to remember to call 
delete, and not being allowed to use something like boost::shared_ptr. I 
agree that GC has taken us a step forward in dealing with memory resources, 
but it seems it was at the cost of not being able to deal with other 
resources as well.

I'm not a compiler expert so I may be way off base. But I think what might 
be nice is if I can define a class as being reference counted instead of 
garbage collected. Then any time you create an instance of that class using 
"new", it would be assigned to a reference-counted reference, not garbage 
collected. The compiler would keep track of that automatically. The user of 
the reference counted class wouldn't have to know or remember to dispose it. 
I know reference counting can have performance penalties, but most of the 
time in my programs it doesn't matter. I'm not creating thousands of 
instances or references but only a few. Another problem cited with reference 
counting is circular references. But let me have the choice. I think I might 
at least alleviate that problem by using the equivalent to boost's weak 
pointers.

Maybe it's better to think of memory and non-memory resources as different 
things and handle them differently as opposed to lumping them together using 
the same mechanism. I'm not sure if there is already a way to deal with this 
in D as I'm not quite that familiar with D.

Jim







More information about the Digitalmars-d mailing list