[C++] move/move_backward
Updated:
개요
- 우측값으로 변환
- 일반적으로 복사 생성자 보다 이동 생성자가 빠르므로 상황에 따라 move 함수를 이용해 이동 생성자가 호출되도록 사용
- move_backward
- 역순으로(마지막 요소가 먼저) 이동
예제
- 코드
#include <iostream> #include <string> #include <vector> using namespace std; void func(int &i) { cout << "func(int &i)" << endl; } void func(int &&i) { cout << "func(int &&i)" << endl; } int main() { int i = 0; func(i); func(3); func(move(i)); func(move(3)); cout << "------" << endl; auto print = [](vector<string> v) { for (const auto &iter : v) { cout << iter << " "; } cout << endl; }; vector<string> v1{"a", "b", "c"}; vector<string> v2{"1", "2", "3", "4"}; move(v1.begin(), v1.end(), v2.begin()); print(v1); print(v2); cout << v1.size() << endl; cout << "------" << endl; vector<string> v3{"a", "b", "c"}; vector<string> v4{"1", "2", "3", "4"}; move_backward(v3.begin(), v3.end(), v4.end()); print(v3); print(v4); cout << v1.size() << endl; return 0; }
- 실행 결과
func(int &i) func(int &&i) func(int &&i) func(int &&i) ------ a b c 4 3 ------ 1 a b c 3