스마트 포인터의 형 변환 - static_pointer_cast

luckyhan studio·2021년 4월 30일
0

스마트 포인터 ( shared_ptr 등 ) 을 사용할 때 생각보다 형 변환이 필요한 경우가 자주 생긴다. 그럴때 static_pointer_cast를 사용하면 쉽게 형변환을 할 수 있다. 아래 간단한 예제 코드로 사용방법을 익혀두자.

사용 예시:

#include <memory>
#include <iostream>

class Parent{
public:
	void print(){
		std::cout << "Parent!" << std::endl;
	}
};

class Child : public Parent{
public:
	void print(){
		std::cout << "Child!" << std::endl;
	}
};

int main(){
	std::shared_ptr<Child> child = std::make_shared<Child>();
	child->print();
	std::shared_ptr<Parent> parent = std::static_pointer_cast<Parent>(child); 
	parent->print();
	return 0;
}

출력화면:

Child!
Parent!

profile
열심히 사는 그냥 개발자

0개의 댓글