swap을 move, copy 할때 차이점 코드
#include <stdio.h>
#include <iostream>
using namespace std;
class Test
{
private :
char *name;
public :
Test(const char* _name) {
cout << "동적할당 함." << endl;
name = new char[strlen(_name) + 1];
strcpy(name, _name);
cout << " base constr" << endl;
}
~Test() {
delete name;
cout << " destr " << endl;
}
Test(const Test &other) {
name = new char[strlen(other.name) + 1];
*name = *other.name;
cout << " copy constr" << endl;
}
Test(Test &&other) : name(other.name){
other.name = 0;
cout << " move constr" << endl;
}
Test& operator=(const Test &other)
{
cout << "동적할당 함." << endl;
name = new char[strlen(other.name) + 1];
*name = *other.name;
cout << "copy 대입" << endl;
return *this;
}
Test& operator=(Test && other)
{
name = other.name;
other.name = 0;
cout << "move 연산자" << endl;
return *this;
}
void print() const
{
cout << *name << endl;
}
};
template <typename T>
void swap_won(T & _a, T & _b)
{
// copy로 처리할 경우
// 동적할당 비용이 2번 더 발생함.
T temp = (_a);
_a = (_b);
_b = (temp);
// move로 처리할 경우.
//T temp = move(_a);
//_a = move(_b);
//_b = move(temp);
}
int main()
{
Test a("wontae");
Test b("zzokki");
a.print();
b.print();
swap_won<Test>(a, b);
a.print();
b.print();
}