|
// Function that takes in a rvalue reference as an argument. |
|
// It appends 3 to the back of the vector passed in as an argument, |
|
// and prints the values in the vector. Notably, it does not seize |
|
// ownership of the vector. Therefore, the argument passed in would |
|
// still be usable in the callee context. |
|
void add_three_and_print(std::vector<int> &&vec) { |
|
vec.push_back(3); |
|
for (const int &item : vec) { |
|
std::cout << item << " "; |
|
} |
|
std::cout << "\n"; |
|
} |
Might change "callee context" to "caller context" in line 53? Since lines 98-107, where add_three_and_print is called, also explained this function won't steal ownership from the caller context lvalue:
|
// If we don't move the lvalue in the caller context to any lvalue in the |
|
// callee context, then effectively the function treats the rvalue reference |
|
// passed in as a reference, and the lvalue in this context still owns the |
|
// vector data. |
|
std::vector<int> int_array3 = {1, 2, 3, 4}; |
|
std::cout << "Calling add_three_and_print...\n"; |
|
add_three_and_print(std::move(int_array3)); |
|
|
|
// As seen here, we can print from this array. |
|
std::cout << "Printing from int_array3: " << int_array3[1] << std::endl; |
15445-bootcamp/src/move_semantics.cpp
Lines 49 to 60 in d6bd76e
Might change "callee context" to "caller context" in line 53? Since lines 98-107, where
add_three_and_printis called, also explained this function won't steal ownership from the caller context lvalue:15445-bootcamp/src/move_semantics.cpp
Lines 98 to 107 in d6bd76e