이번 회는 Move 생성자와 Move 대입 연산자를 정의 했을 때 어떤 결과가 나오는지, 그리고 std::move 라는 것에 대해서 이야기 하겠습니다.
복사 생성자와 대입 연산자만 정의했을 때
< Code 1. 복사 생성자와 대입 연산자 정의 >
class NPC
{
public:
int NPCCode;
string Name;
NPC()
{
cout << "기본 생성자" << endl;
}
NPC( int _NpcCode, string _Name )
{
cout << "인자가 있는 생성자" << endl;
}
NPC(NPC& other)
{
cout << "복사 생성자" << endl;
}
NPC& operator=(const NPC& npc)
{
cout << "대입 연산자" << endl;
return *this;
}
};
int main()
{
NPC npc1( NPC( 10,"Orge1") );
NPC npc2(11,"Orge2");
NPC npc3 = npc2;
NPC npc4;
NPC npc5;
npc5 = npc4;
return 0;
}
< 결과 >
당연한 결과가 나왔죠^^
그럼 <Code 1>에 Move 생성자와 Move 대입 연산자를 정의하고 결과를 보겠습니다.
Move 생성자와 Move 대입 연산자 정의
< Code 2. Move 생성자와 Move 대입 연산자 정의>
class NPC
{
public:
int NPCCode;
string Name;
NPC()
{
cout << "기본 생성자" << endl;
}
NPC( int _NpcCode, string _Name )
{
cout << "인자가 있는 생성자" << endl;
}
NPC(NPC& other)
{
cout << "복사 생성자" << endl;
}
NPC& operator=(const NPC& npc)
{
cout << "대입 연산자" << endl;
return *this;
}
NPC(NPC&& other)
{
cout << "Move 생성자" << endl;
}
NPC& operator=(const NPC&& npc)
{
cout << "Move 대입 연산자" << endl;
return *this;
}
};
int main()
{
cout << "1" << endl;
NPC npc1( NPC( 10,"Orge1") );
cout << endl << "2" << endl;
NPC npc2(11,"Orge2");
NPC npc3 = npc2;
cout << endl << "3" << endl;
NPC npc4; NPC npc5;
npc5 = npc4;
cout << endl << "4" << endl;
NPC npc6 = NPC(12, "Orge3");
cout << endl << "5" << endl;
NPC npc7; NPC npc8;
npc8 = std::move(npc7);
return 0;
}
< 결과 >
아래 코드는 Move 생성자를 정의해서 예전에는 ‘복사 생성자’가 호출되었지만 이제 ‘Move 생성자’가 호출 됩니다.
std::move
NPC npc2; NPC npc3;
npc3 = npc2;
에서는 대입 연산자가 호출되는데 이것을 ‘Move 대입 연산자’가 호출되도록 하기 위해서 C++0x에서 새로 생긴 std::move()를 사용합니다.
NPC npc7; NPC npc8;
npc8 = std::move(npc7);
std::move는 Move Semantics를 위해 이번에 새롭게 추가된 것입니다.
이것은 좌측 값(LValue)을 우측 값(RValue)으로 변환하기 위한 함수입니다.
std::move는 RValue Reference한 오브젝트의 멤버를 이동할 때도 사용합니다.
NPC( NPC&& npc) : Name(std::move(npc.Name)), NPCCode(std::move(npc.NPCCode))
{
………
}
std::move는 <utility>에 정의 되어 있습니다.
namespace std {
template <class T>
inline typename remove_reference<T>::type&& move(T&& x)
{
return x;
}
}
'C++0x' 카테고리의 다른 글
| [VC++] 8. 우측 값 참조( RValue Reference ) – 다섯 번째 (3) | 2009/05/26 |
|---|---|
| [VC++] 7. 우측 값 참조( RValue Reference ) - 네 번째 (3) | 2009/05/20 |
| [VC++] 6. 우측 값 참조( RValue Reference ) - 세 번째 (0) | 2009/05/09 |
| [VC++] 5. 우측 값 참조( RValue Reference ) – 두 번째 (2) | 2009/05/06 |
| [VC++] 4. 우측 값 참조( RValue Reference ) - 첫 번째 (2) | 2009/05/04 |
| [VC++] 3. static_assert (0) | 2009/04/27 |




댓글을 달아 주세요