Boost logo

Boost :

From: Jonathan Turkanis (technews_at_[hidden])
Date: 2005-02-14 14:41:02


Chris Just wrote:

>> The problem is that the code which transfers ownership appears
>> innocuous on the surface, because auto_ptr allows transfer of
>> ownership with the same syntax ordinarily used for copying:
>>
>> void f()
>> {
>> auto_ptr<int> ptr(new int);
>> auto_ptr<int> ptr2(ptr); // ptr is now empty.
>> }
>
> Why would anyone in their right mind do that?

By accident, perhaps? The point is, why allow such errors to creep into code
when they can be prevented at compile time?

>> Declaring a function to take an argument of type auto_ptr<...> is
>> one way to signal that ownership is being transfered to the
>> function. It also ensures that the managed object will be deleted,
>> unless the function takes explicit steps to cause a leak. Passing
>> raw pointers defeats this system.
>
> Yes, this is true if you're calling a function that you wrote and
> compiled yourself, but if you're calling a 3rd party API that you
> didn't compile yourself, that can be dangerous (or so I've been told).

Dangeous how? Actually the opposite is true: if you declare such a function to
take a raw pointer, callers might think they still own the pointer after calling
the function, or the function might not clean up the resource properly.

>>> How? If you pass a pointer to a function, you shouldn't be deleting
>>> it inside that function anyways (so pass it with .get()),
>>
>> What if you want to transfer ownership to the function, as is often
>> the case?
>
> Then pass ptr.release() to the function.

See above.

>>> and if you
>>> return a pointer from a function, you can save it in a new AutoPtr
>>> so it will get deleted automatically...
>>
>> This depends on the calling code to do the right thing. If you
>> return an auto_ptr, the managed object will be freed even if the
>> calling code choses to ignore the return value.
>
> I agree, if it's your own code, return an auto_ptr, but if you're an
> API, you must return a raw pointer.

Why?

>>> I don't set my pointer to NULL when I release() it, I just set
>>> m_Owner = false.
>>
>> This behavior is not compatible with std::auto_ptr.
>
> I could change it to set the pointer to NULL, but this is what
> Microsoft's auto_ptr does, and it looked safer.

The old Dinkumware library that shipped with VC5-6 is not a good model.

>> move_ptr has the same overhead as auto_ptr.
>
> Thanks, when I get some time I'll take a look at those.
>
> As you might infer from some of my comments, I'm dealing mostly with
> API component code myself, which integrates some older sub
> components, so I have no choice but to pass raw pointers most of the
> time.

Yes, we all have to do this sometimes.

> Chris Just

Jonathan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk