티스토리 뷰

placement 문법이란, 내가 malloc등으로 생성한 동적 memory를 type 캐스팅을 통해 클래스로 변환하였을 경우,

생성자 호출이 되지 않는데 이러한 상황에서 생성자를 호출하는 방법이다.

 

정리

void* ptr = malloc(size) -> ptr을 static_cast<class> 등을 통해 형변환 후

new(ptr)클래스이름(인자) 로 생성자 호출(초기화)

 

고로 내가 원하는 데이터 영역을 할당하여 사용할 수 있게 된다.

(굳이 malloc 말고, 이미 만들어진 데이터 공간도 크기만 맞다면 가능)

 

 

※ std::forward 같은 경우에는 args로 들어온 값을 인자로써 들어갈 수 있도록 해주는 함수입니다.

 

template<class T, typename... types>
T* xnew(types... args)
{
	// placement new
	void* ptr = malloc(sizeof(T));
	T* _ptr = static_cast<T*>(ptr);
	new(_ptr)T(std::forward<types>(args)...);

	return _ptr;
}

template<class T>
void xdelete(T* ptr)
{
	// 소멸자 호출
	ptr->~T();
	free(ptr);
}

 

아래는 테스트 코드입니다.

더보기
class Test
{
public:
	Test() : _a(0) { cout << "생성자 1 호출" << endl; }
	Test(int a) : _a(a) { cout << "생성자 2 호출" << endl; }
	~Test() { cout << "소멸자 호출" << endl; }

	void Set(int a) { _a = a; }
	void Print() { cout << _a << endl; }
private:
	int _a;
};

int main()
{
	Test* test = xnew<Test>();
	Test* test2 = xnew<Test>(1);

	xdelete(test);
	xdelete(test2);

}

'프로그래밍 언어 > C++' 카테고리의 다른 글

STLAllocator  (0) 2023.04.02
VirtualAlloc - PAGE 크기로 동적 할당  (0) 2023.04.02
shared_ptr 구현기 - 1일차  (0) 2023.03.27
C++) STL 목차 정리  (0) 2022.11.24
씹어먹는 C++) SpinLock 구현 및 15-3-1 문제 풀이  (0) 2022.11.22
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함