CS 23001 CS II Data Structures and Abstraction
CS 23001 CS II: Data Structures and Abstraction R-Value References Xiang Lian Department of Computer Science Kent State University Email: xlian@kent. edu Homepage: http: //www. cs. kent. edu/~xlian/ 1
Objectives • R-Value References – Examples – Syntax • Move Constructor • Move Assignment 2
Introduction • Rvalue references are a feature of C++ • l-value vs. r-value – int a = 2; – int b = 3; // a and b are both l-values – a = a * b; // ok – int c = a*b; // a*b is a r-value – a*b = 42; // error: assigning a constant to a r-value 3
Rvalue References • If X is any type, then X&& is called an rvalue reference to X • For better distinction, the ordinary reference X& is now also called an lvalue reference – void foo(X& x); // lvalue reference overload – void foo(X&& x); // rvalue reference overload 4
Examples of Rvalue References • void foo(X& x); // lvalue reference overload • void foo(X&& x); // rvalue reference overload //////////main() function///////////// • X x; • X foobar(); • foo(x); // argument is lvalue: calls foo(X&) • foo(foobar()); // argument is rvalue: calls foo(X&&) 5
Move Constructor • A move constructor allows the resources owned by an rvalue object to be moved into an lvalue without creating its copy • Syntax of move constructor: – class_name ( class_name && ) • Copy constructor vs. move constructor – class_name ( class_name & ) 6
Move Constructor (cont'd) • class_name ( class_name && src_obj) – assign the class data members from the source object to the object that is being constructed – Assign the data members of the source object to default values 7
Move Assignment class_name& operator=(class_name&& src_obj) { if (this != &src_obj) { delete [] data; // deallocate the space data = src_obj. data; // copy the data pointer // from the source object src_obj. data = NULL; // release the data pointer from // the source object so that the // destructor does not free the // memory multiple times. } return *this; 8 }
Calling of Move Constructor and Assignment • The move constructor and move assignment are called when those functions have been defined • The argument for construction or assignment is an r-value • Most typically, this r-value will be a literal or temporary value 9
Code • String • … 10
11
- Slides: 11