C++ std::pair<std::vector<int>, int> 같은 걸 리턴할 때 pair의 first에 std::move를 안 붙여주면 복사가 일어납니다!

올드하게 std::make_pair로 리턴하든 {} 문법으로 리턴하든 마찬가지입니다.


예제 코드:


#include <algorithm> #include <iostream> #include <vector> using namespace std; struct Vector { vector<int> v; Vector() = default; Vector(const Vector& other) : v{other.v} { cout << "Copy ctorn"; } Vector& operator=(const Vector& other) { Vector V{other}; swap(*this, V); cout << "Copy asgnn"; return *this; } Vector(Vector&& other) noexcept : v{move(other.v)} { cout << "Move ctorn"; } Vector& operator=(Vector&& other) noexcept { Vector V{move(other)}; swap(*this, V); cout << "Move asgnn"; return *this; } }; pair<Vector, int> func() { cout << "func()n"; Vector V; V.v.push_back(1); V.v.push_back(2); return {V, 1}; } pair<Vector, int> func2() { cout << "func2()n"; Vector V; V.v.push_back(1); V.v.push_back(2); return {move(V), 1}; } int main() { func(); func2(); }



실행 결과 (https://wandbox.org/permlink/QqO3vdJOoEd8JGAn)


func()

Copy ctor

func2()

Move ctor


이걸로 데여본 분들은 다 명심하게 되는 사항이지만,


초심자 분들은 pair 쓸때 주의합시다.