[일반]
C++ pair 리턴할 때 주의점
익명(skuld88)
2022-07-19 16:20
추천 3
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 쓸때 주의하세요
move써도 되긴하는데 전역변수 같은기로 때려박고 index로 관리하는 스타일이 더 많은듯
전역변수.. 너무 PS식..
ps갤에서 ps식으로 하지 그럼 뭔 ㅋㅋ