Josh Dybnis on 6 Jul 2003 19:36:02 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [ALACPP] smart pointers in C


--- Christopher Smith <x@xxxxxxxx> wrote:
> Josh Dybnis wrote:
>>--- Christopher Smith <x@xxxxxxxx> wrote:
>>>On Wed, 2003-07-02 at 07:43, Josh Dybnis wrote:
>>>
>>>>I don't think that it is possible to do smart pointers in C. The
>>>>reason why, is that there is no way in C to associate a piece of 
>>>>code with a value, in such a way that the code is automatically 
>>>>executed when the value is stored into a variable, or conversly 
>>>>when the value is taken out of a variable (either because the 
>>>>variable goes out of scope or another value is stored in it). In 
>>>>C++ this can be done with constructors, a destrutor, a copy 
>>>>constructor, and an overloaded assignment operator.
>>>>      
>>>In C you can do smart pointers through the mechanisms like handles.
>>>It's not as pretty as the C++ approach, but it works.
>>>    
>>Can you elaborate on this, or give a reference?
>>
>Umm... pretty much any OS or GUI environment provides you with
>handles, which are typically some kind of an int which provides an 
>indirect reference (typically through a lookup table of some kind) to 
>the real pointer. Functions are provided for opening, copying (well, 
>not always copying) and closing the handle. Each of the functions 
>updates internal structures which manage the actual resources the 
>handle is associated with, including ref-counts. Typically you never 
>get direct access to the real data structure, although in some crazy 
>cases the int's value is the same as the address value of the
>pointer. Because you are dealing with C instead of C++, using the 
>copy operator will simply do a bitwise copy without updating any 
>refs. Also, you don't have destructors, so you have to explicitly 
>ensure that you close a handle before it falls out of scope.
> 
>Like I said, it isn't pretty, but it essentially provides a resource 
>management abstraction.
> 
> --Chris

Good point, handles do provide some abstraction. But I still stand by
my statement that smart pointers can not be done in C. When all you
have is a bitwise copy, you can't even do something like a
std::auto_ptr. Some smart-pointer like functionality is possible, but
in a very limited way. With a ref-counted handle, you get "the last one
out the door, turns out the lights" resource managment. The handle will
clean up its resources when there are no more open references to it.
That's not enough to prevent a leak when someone forgets to close the
handle before it goes out of scope. No such mistake is possible with
the smart pointers implemented in the book.

-Josh
_______________________________________________
alacpp mailing list
alacpp@xxxxxxxxxxx
http://lists.ellipsis.cx/mailman/listinfo/alacpp