|
Boost : |
From: Beman Dawes (bdawes_at_[hidden])
Date: 2002-02-04 20:24:46
At 07:37 PM 2/4/2002, Jon Kalb wrote:
>Howard,
>
>Is move what we really want? Or is it swap? I've thought for awhile that
>swap was a missing "operator." It seems to be such a fundamental
>operation.
>
>I think it is clear what swap means, but I'm not certain that it is
>always going to be obvious what the state of an object is that has been
>"moved from." Does it assume the state of the default value? What if
>there is no default constructor? What if the default constructor does an
>allocation in preparation of storing data? Would that mean that move
>could fail?
>
>Note that if auto_ptr swapped instead of moved it would have almost the
>same behavior when being passed or returned. Consider returning by
>auto_ptr:
>
>auto_ptr<Foo> FooBar()
>{
> auto_ptr<Foo> result(new Foo(A));
>}
>
>...
>auto_ptr<Foo> dest(new Foo(B));
>dest = FooBar();
>...
>
>Currently dest will delete its pointer to Foo(B) and accept the pointer
>to Foo(A) from result which gives up ownership of Foo(A) and is
>destructed.
>
>With swap semantics, dest trades pointers with result and result deletes
>the pointer to Foo(B) when it is destructed.
>
>I'm not suggesting that we change the semantics of auto_ptr at this late
>date. Code like this would do something the author hadn't intended:
>
>auto_ptr<Foo> a(new Foo), b(new Foo); a = b;
>
>What I am saying is that I think swap semantics accomplish what you want
>to accomplish with move, but is "more fundamental." Herb Sutter has
>convinced me that if I want to write exception safe code, I need to
>create a swap operation anyway and if I could use that operation to
>accomplish what you want to accomplish with move, I think it's a win.
I assume Jon's reference to Herb Sutter is to Herb's "Exceptional C++"
(Addison Wesley) which I was just reading the other day. While reading
items 8 through 19, I kept wondering if some of the uses of swap Herb is
advocating wouldn't better be served by move. While swap would always
work, move might generate less code in the cases where it was
applicable. But I haven't done the analysis, so don't have an opinion
yet. I think there is a (swap vs move) rule-of-thumb hiding there, but I'm
not smart enough to identify it without a lot more study.
--Beman
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk