상세 컨텐츠

본문 제목

[C++11] Special member functions for move semantics

C++/Modern C++(11, 14, 17, 20)

by deulee 2023. 8. 24. 17:18

본문

복사 생성자와 복사 대입 연산자는 복사본이 만들어질 때 호출됐었다.

 

하지만 C++11의 `move semantics`가 생기면서 `move constructor``move assignment operator`를 만들 수 있게 되었다.

 

#include <iostream>

class B {
public:
	std::string s;
	B() : s{"test"} {std::cout << "B constructor" << std::endl;}
	B(const B& o) : s{o.s} {std::cout << "B copy constructor" << std::endl;}
	B(B&& o) : s{std::move(o.s)} {std::cout << "B move copy constructor" << std::endl;}
	B& operator=(const B& r) {s = o.s; return *this;}
	B& operator=(B&& r) {
    	s = std::move(o.s);
		std::cout << "move assignment called" << std::endl;
		return *this;
	}
	~B() {std::cout << "B destructor" << std::endl;}
};

B fb(B b)
{
	return b;
}

int main(void)
{
	B b1 = fb(B{}); // move-constructed from rvalue temporary
	B b2 = std::move(b1); // move-constructed using std::move
	B b3 = B{};
	b2 = std::move(b3); // move-assignment using std::move
	b1 = fb(B{}); // move-assignment from rvalue temporary
	return 0;
}

그럼 이를 통해 무슨 이점이 있을까?

 

`이동 생성자(move constructor)`는 객체의 소유권을 다른 객체로 이전하는 역할을 한다. 보통 이동 생성자는 우측값 참조를 매개변수로 받는다. 복사 대신 객체의 내부 데이터(메모리 등)의 소유권을 이전하여 효율적인 이동을 수행한다. 이로써 임시 객체나 이동 가능한 객체를 더 효율적으로 처리할 수 있다.

 

`이동 대입 연산자(move assignment operator)` 또한 이미 생성된 객체에 다른 객체의 소유권을 이전하는 역할을 한다.

 

즉, 효율적인 메모리 관리를 구축할 수 있다.

관련글 더보기