Raees Rajwani
Raees Rajwani

Reputation: 517

Difference in implementation between two insert() method signatures for std::list

The method insert() for std::list has 2 method signatures. One takes a const lvalue reference as so:

iterator insert( const_iterator pos, const T& value );

The other takes a rvalue reference as so:

iterator insert( const_iterator pos, T&& value );
  1. However I was wondering why the second method signature was even necessary? A const lvalue reference can bind to rvalues.

I am aware that it may be faster to move rvalues instead of copy them.

  1. However, how will the second method signature that takes a rvalue reference implement a move instruction on value that differs from the first that takes a const lvalue reference?

The assignment operator on rvalues will simply call the move constructor while on an lvalue it will call the copy constructor. So simply using an assignment operator in the first function should suffice right?

Thank you

Upvotes: 0

Views: 48

Answers (1)

user2486888
user2486888

Reputation:

Firstly, T&& here is not universal reference, but an rvalue reference, because T is not deduced at the moment of function call. It is known at the moment the class template is instantiated.

However I was wondering why the second method signature was even necessary? A const lvalue reference can bind to rvalues.

To leverage move semantics. Taking rvalue reference enable move operation.

However, how will the second method signature that takes a rvalue reference implement a move instruction on value that differs from the first that takes a const lvalue reference?

The difference is: taking const lvalue reference cannot move at all; only taking rvalue reference can move.

Upvotes: 2

Related Questions