Problem 5
Implement the move features:
• List( List&& aOtherList ),
• List& operator=( List&& aOtherList ),
• void push_front( T&& aElement ),
• void push_back( T&& aElement ).
The move features “steal” the memory of the argument. That is, calling the copy constructor or using the assignment operator leaves aOtherList empty. Similarly, calling push_front() and push_back(), respectively, leaves aElement empty.
The move variants are chosen be the compiler if the argument is a temporary or literal expression.
To force move semantics we have to use, where necessary, the std::move() function, which performs a type conversion on its argument that guarantees that the argument is an r value reference.
You can use #define P5 in Main.cpp to enable the corresponding test driver.
void testP5()
{
using StringList = List<string>;
string s2( "CCCC" );
List<string> lList;
cout << "Test of problem 5:" << endl;
lList.push_front( string( "DDDD" ) );
lList.push_front( std::move(s2) );
lList.push_front( "BBBB" );
if ( s2.empty() )
{
cout << "Successfully performed move operation." << endl;
}
else
{
cerr << "Error: Move operation failed." << endl;
}
cout << "A - Top to bottom " << lList.size() << " elements:" << endl;
for ( const string& element : lList )
{
cout << element << endl;
}
List<string> move( std::move(lList) );
if ( lList.empty() )
{
cout << "Successfully performed move operation." << endl;
}
else
{
cerr << "Error: Move operation failed." << endl;
}
// iterate from the top
cout << "B - Top to bottom " << move.size() << " elements:" << endl;
for ( const string& element : move )
{
cout << element << endl;
}
// override list
lList = std::move(move);
if ( move.empty() )
{
cout << "Successfully performed move operation." << endl; }
else
{
cerr << "Error: Move operation failed." << endl;
}
lList.push_front( "AAAA" );
lList.push_back( "EEEE" );
// iterate from the top
cout << "C - Bottom to top " << lList.size() << " elements:" << endl;
for ( auto iter = lList.rbegin(); iter != iter.rend(); iter-- ) {
cout << *iter << endl;
}
cout << "Completed" << endl;
}
The result should look like this:
Test of problem 5:
Successfully performed move operation.
A - Top to bottom 3 elements:
BBBB
CCCC
DDDD
Successfully performed move operation.
B - Top to bottom 3 elements:
BBBB
CCCC
DDDD
Successfully performed move operation.
C - Bottom to top 5 elements:
EEEE
DDDD
CCCC
BBBB
AAAA
Completed
Students succeed in their courses by connecting and communicating with an expert until they receive help on their questions
Consult our trusted tutors.