Re: rvalue reference questions
Faisal wrote:
I was reading about rvalue refernces in this link
http://www.artima.com/cppsource/rvalue.html
Most of the thing seems clear to me. But I'm confused in certain
parts
For eg:
In the section Overloading on lvalue / rvalue
<quote>
class Derived
: public Base
{
std::vector<int> vec;
std::string name;
// ...
public:
// ...
// move semantics
Derived(Derived&& x) // rvalues bind here
: Base(std::move(x)),
vec(std::move(x.vec)),
name(std::move(x.name)) { }
Derived& operator=(Derived&& x) // rvalues bind here
{
Base::operator=(std::move(x));
vec = std::move(x.vec);
name = std::move(x.name);
return *this;
}
// ...
};
Note above that the argument x is treated as an lvalue internal to
the move functions, even though it is declared as an rvalue
reference parameter. That's why it is necessary to say move(x)
instead of just x when passing down to the base class. This is a
key safety feature of move semantics designed to prevent
accidentally moving twice from some named variable. All moves occur
only from rvalues, or with an explicit cast to rvalue such as using
std::move. If you have a name for the variable, it is an lvalue.
</Quote>
In this case how the compiler convert the rvalue reference parameter
as lvalue?
There is no conversion, it is just treated as an lvalue. Like the
quote says, an rvalue is usually an unnamed temporary. The parameter
is not, but the value it is bound to is the rvalue.
And when the question of double-moving comes? Can someone give an
example.
You can just think about what happens if you try to move from a value
twice:
vec1 = std::move(x.vec);
vec2 = std::move(x.vec);
Here vec1 gets the value from x.vec, which is then empty. Then vec2
gets nothing!
On the other hand, here
vec1 = x.vec;
vec2 = x.vec;
vec1 and vec2 both get a copy of x.vec (which also retains its value).
Bo Persson