I have found the following snippet in a code implementing a list
class
void push_front( const T & x ) { insert( begin( ), x ); }
void push_front( T && x ) { insert( begin( ), std::move( x ) );}
Now I know that if I have a function taking a parameter as an r-value
, that parameter will be l-value
in the scope of the function (Isn't that right?).
So I can replace the previous snippet by
void push_front( const T & x ) { insert( begin( ), x ); }
void push_front( T && x ) { push_front( x );}
The first question: Am I right?
The second one: By considering that the r-value
parameter in the first snippet is an l-value
parameter inside the second function, Will std::move( x )
cast x
from l-value
to r-value
and the function push_front()
call the r-value
version of the function insert()
or what?
An edit::
This is how insert()
is implemented
iterator insert( iterator itr, const T & x )
{
Node *p = itr.current;
theSize++;
return { p->prev = p->prev->next = new Node{ x, p->prev, p } };
}
iterator insert( iterator itr, T && x )
{
Node *p = itr.current;
theSize++;
return { p->prev = p->prev->next = new Node{ std::move( x ), p->prev, p } };
}
The definition of Node
struct Node
{
private:
T data;
Node *prev;
Node *next;
Node( const T & d = T{ }, Node * p = nullptr,
Node * n = nullptr )//It's possible because of const
:data{ d }, prev{ p }, next{ n } { }
Node( T && d, Node * p = nullptr, Node * n = nullptr )
: data{ std::move( d ) }, prev{ p }, next{ n } { }
};
I have a function taking a parameter as an r-value, that parameter will be l-value in the scope of the function
Yes. In general, all rvalue reference variables are lvalues, function parameters or not.
So I can replace the previous snippet by ...
Yes, but then push_front(T &&x)
will copy x
instead of moving it.
Will
std::move( x )
cast x from l-value to r-value and the functionpush_front()
call the r-value version of the functioninsert()
Yes.