Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2002-09-21 16:25:48


On Saturday, September 21, 2002, at 12:06 PM, Peter Dimov wrote:

> A swap-capable scoped_ptr is the best solution. [for implementing
> handle/body]

I agree in the context of the current language.

If move_ptr comes to be, I think move_ptr might be a better solution.

Rationale: scoped_ptr::swap is just another name for move assignment
on scoped_ptr. It transfers resources. In the context of move
semantics, it seems odd that a class does not have move semantics
(especially move assignment) yet supports a resource transferring swap.

If a handle/body used move_ptr as an implementation, the handle copy
constructor and copy assignment would be implemented in the same
fashion as with scoped_ptr. And the compiler generated versions would
compile-time like scoped_ptr. (the move_ptr in the proposal is
currently lacking a swap function, but that is of course easily
repaired)

What if the handle/body wanted to implement move semantics? It might
look like:

Handle::Handle(Handle&& h)
     : impl_(static_cast<Ptr&&>(h.impl_))
{
}

Handle&
Handle::operator=(Handle&& h)
{
     impl_ = static_cast<Ptr&&>(h.impl_);
     return *this;
}

(Ptr is a typedef for the move_ptr)

With scoped_ptr the move constructor is still doable, but perhaps not
as intuitive (but that's a judgment call). You have to take advantage
of the fact that the only way to transfer scoped_ptr's resource is via
swap. That is, you need to default construct the target scoped_ptr
first, and then swap with the source:

Handle::Handle(Handle&& h)
{
     impl_.swap(h.impl_);
}

And move assignment can also be accomplished with swap.

Handle&
Handle::operator=(Handle&& h)
{
     impl_.swap(h.impl_);
     return *this;
}

I find myself wondering what is the niche that scoped_ptr fills better
than move_ptr. And my best guess right now is the role of a local auto
variable where the resource never needs to be transferred out of the
scoped_ptr.

-Howard


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