[xsd-users] use of auto_ptr

Boris Kolpackov boris at codesynthesis.com
Wed Apr 4 06:16:20 EDT 2007


Hi Guy,

Guy Kroizman <kroiz at hyperroll.com> writes:

> why is it impossible to write exception-safe code using naked pointers?

This is a complicated issue. In a few words it has to do with the
possibility of an exception being thrown while nobody "own" the
naked pointer. The two situations in this case are:

(1) One of the argument's destructor could throw. For example, assuming
    foo() returns a dynamically allocated object as a naked pointer:

    foo_t* f = foo ("foo.xml", 0 , xml_schema::properties ());

    Here if the temporary for the third argument throws during destruction
    the object will be leaked. This situation is somewhat far-fetched
    because destructors normally do not throw.

(2) The second situation is a lot more real. Suppose you have a
    function that takes two arguments:

    class bar_t {...};
    void f (foo_t*, const bar_t&);

    And you do something like this:

    f (foo ("foo.xml"), bar ());

    The C++ standard does not specify the order in which arguments
    are evaluated. So it is possible that foo("foo.xml") will be
    called first and bar() second. If bar's constructor throws,
    then the object returned by foo() is leaked.


> As you suggested before, I could keep the naked pointer as a member in a
> class the will destroy it in the destructor.
> that is exception-safe. right?

It can be made exception-safe but it is a lot of work if you keep naked
pointers around. It is easier to make each member clean-up after itself
automatically by using smart pointers. For more on this see, for example,
this C++ FAQ entry:

http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.4


hth,
-boris
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 652 bytes
Desc: Digital signature
Url : http://codesynthesis.com/pipermail/xsd-users/attachments/20070404/e226d5b9/attachment.pgp


More information about the xsd-users mailing list