move

phoenixKim·2022년 4월 18일
0

temp

목록 보기
11/11

swap을 이용한 사용 예시

복사를 피하기 위해서 move를 사용하자.

공부하지 않았을 때, copy 발생

: 소유권이 이전되지는 않음.

#include <iostream>
#include <string>
using namespace std;


class Test
{
public : 
	Test(string name) 
	{
		name_ = name; 
		cout << "constr" << endl; 
	}
	~Test()
	{
		cout << "destr" << endl; 
	}
	Test(const Test&other)
		: name_(other.name_)
	{ 
		cout << "copy" << endl; 
	}
	Test(Test&& other)
		: name_(move(other.name_))
	{
		if (other.name_ == "")
		{
			cout << "공백" << endl;
		}
		cout << "move" << endl;
	}

	Test& operator=(const Test&t)
	{ 
		name_ = (t.name_);
		if (t.name_ == "")
		{
			cout << "공백" << endl;
		}
		else
		{
			cout << "소유권 이전되지는 않음." << endl;
		}
		cout << "copy 대입" << endl;
		return *this;
	}
	Test& operator=(Test&&t) 
	{ 
		name_ = move(t.name_);
		if (t.name_ == "")
		{
			cout << "공백" << endl;
		}
		cout << "move 대입" << endl;
		return *this; 
	}
public : 
	string name_;
};

template <typename T>
void Swap(T &a, T & b)
{
	Test s = (a);
	a = (b);
	b = (s);
}


int main()
{
	Test a("wontae");
	Test b("zzokki");
	Swap(a, b);

	cout << a.name_ << endl;
	cout << b.name_ << endl;
}

move를 사용할 경우

: 소유권이 이전되는 것을 확인할 수 있음.

#include <iostream>
#include <string>
using namespace std;


class Test
{
public : 
	Test(string name) 
	{
		name_ = name; 
		cout << "constr" << endl; 
	}
	~Test() { cout << "destr" << endl; }
	Test(const Test&other) { cout << "copy" << endl; }
	Test(Test&& other)
		: name_(move(other.name_))
	{
		if (other.name_ == "")
		{
			cout << "공백" << endl;
		}
		cout << "move" << endl;
	}

	Test& operator=(const Test&t) { return *this; }
	Test& operator=(Test&&t) 
	{ 
		name_ = move(t.name_);
		if (t.name_ == "")
		{
			cout << "공백" << endl;
		}
		cout << "move 대입" << endl;
		return *this; 
	}
private : 
	string name_;
};

template <typename T>
void Swap(T &a, T & b)
{
	Test s = move(a);
	a = move(b);
	b = move(s);
}


int main()
{
	Test a("wontae");
	Test b("zzokki");
	Swap(a, b);
}

// 결과

-> 공백을 통해서 내부 string 값의 소유권이 이전되는 것을 확인할 수 있음.

profile
🔥🔥🔥

0개의 댓글

관련 채용 정보