move

3700 ワード

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値の所有権遷移は、スペースで決定できます.