Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2002-09-21 11:55:01


From: "Peter Dimov" <pdimov_at_[hidden]>
> From: "David Abrahams" <dave_at_[hidden]>
> > Almost. There's swap().
>
> True. scoped_ptr::swap is "my fault". It still doesn't let you leak
memory,
> so it's not as bad as a release(); it's provided to support the
"scoped_ptr
> as a class member" usage, where auto_ptr's copy/assignment semantics lead
to
> implicitly generated members that are often (always?) not what is
desired.
> The motivation, to quote from earlier e-mails to Beman, Greg, and Darin:
>
> "The documentation states that "one common usage of scoped_ptr is to
> implement a handle/body idiom." One common usage of the handle/body idiom
is
> to achieve strong exception safety by using the "construct temporary and
> swap" idiom; however, scoped_ptr doesn't have swap(), so users are forced
to
> use raw pointers."

Wow, time passes. I seem to remember that I once made that argument ;-)

> My point is that swap() is a requirement for scoped_ptr when used as a
> member; it enables replacing raw owning pointers with scoped_ptr's.
>
> The principal drawbacks of using a raw pointer as a member is that it has
> default semantics of the "big three"

Big three?

> that are usually incorrect. scoped_ptr
> is a perfect solution to this problem, since it defines a correct
destructor
> and disables the copy constructor and the assignment operator by default,
> forcing the class to implement the proper semantics.

Yup.

> The problem is that without swap(), it's not possible to implement a
> copyable class with a scoped_ptr member. With swap(), it's trivial.

Huh?

    struct body {};
    struct handle {
        scoped_ptr<body> impl;
        handle() : impl(new body) {}
        handle(handle const& rhs)
            : impl(new body(*rhs.get())) {}
    };

Maybe you meant s/assignable/copyable/?

> Another peculiarity is that swap() is a lower-level primitive than
reset()
> (reset can be implemented on top of swap.)
>
> For a discussion on using a pointer member to achieve strong exception
> safety, see:
>
> http://www.gotw.ca/gotw/059.htm

Uh, thanks, I think I invented that idiom. Too bad its importance is always
overplayed ;-/.

-Dave

-----------------------------------------------------------
           David Abrahams * Boost Consulting
dave_at_[hidden] * http://www.boost-consulting.com


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