Re: Is self assignment test valid?
On Sep 5, 2:34 am, Andrei Alexandrescu <and...@cs.washington.edu>
wrote:
JoshuaMaur...@gmail.com wrote:
On Sep 4, 3:37 pm, David Abrahams <d...@boostpro.com> wrote:
on Thu Sep 04 2008, Ulrich Eckhardt <doomster-AT-knuut.de> wrote:
I guess the alternative that Maciej was thinking about (but never actually
mentioned) was the copy and swap approach:
operator=( T const& other)
{
T tmp(other); // make a copy
swap( *this, tmp);
return *this;
}
That's the wrong way to write it, though ;-). On real compilers
operator=( T other )
{
swap( *this, other);
return *this;
}
can be *much* more efficient because of copy elision.
Cheers,
{ quoted signature and banner removed -mod }
I just reviewed the standard to make sure I didn't forget something,
but I'm totally not seeing what you're talking about David Abrahams. I
see exactly copy constructor call in both your example code and in
Ulrich Eckhardt's code. The single copy constructor cannot be elided
because the temporary needs to be created to be swapped with *this.
As an aside, the way I've generally done it is as follows, which I
assume to be equivalent to the two previous examples.
struct T
{
T& operator= (T const& x)
{
T(x).swap(*this);
return *this;
}
void swap(T& x);
};
That's the politically correct version. It turns out that, when a
function needs to make a copy of its argument, it better takes it by
value in the first place. That way, if an rvalue is passed in, the
compiler can directly fuse the rvalue to the parameter thus saving a copy.
Seehttp://www.erdani.org/publications/cuj-02-2003.html. In short,
again, whenever a function plans to make a copy of its argument, it is
correct and recommendable to just have the function take the argument by
value. That includes the assignment operator. I even managed to convince
Herb to introduce that rather unusual (at that time) recommendation in
the C++ Coding Standards book.
Ok. I see and agree.
Alas, that rule cannot engulf the copy constructor. I believe that's a
rather gratuitous limitation. Many, many, very many things would have
been simpler had that limitation not been in place, sigh.
Now, this makes no sense. What is your alternative, a copy constructor
that takes arguments by value? But how is that argument object
constructed? A copy constructor must take its argument by reference.
There has to be some code somewhere which defines how to copy your
object. That code must take its input by reference as it cannot take
the input by value. That code is the copy constructor.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]