C++ TIPS

#define을 활용하여 만드는 편리한 매크로들

hyrule 2022. 4. 7. 14:44

* 동적할당한 변수를 지워주는 매크로 함수

#define SAFE_DELETE(p) if(p) {delete p; p = nullptr;}

* 동적할당한 배열을 지워주는 매크로 함수

#define SAFE_DELETE_ARRAY(p) if(p) { delete[] p; p = nullptr;}

* #define을 사용할 때 \를 사용하면 바로 아래줄의 코드를 올려서 붙여주어 한줄로 인식시켜 준다.
 *** 가장 마지막줄은 \을 빼  주어야 한다.

* 이를 이용하여, 싱글턴 패턴 클래스를 편리하게 만들어 주는 define 매크로를 만들 수 있다.

 

*싱글턴 패턴 선언 매크로

#define	DECLARE_SINGLE(Type)	\
private:\
	static Type*	m_Inst;\
public:\
	static Type* GetInst()\
	{\
		if (m_Inst == nullptr)\
			m_Inst = new Type;\
		return m_Inst;\
	}\
	static void DestroyInst()\
	{\
		SAFE_DELETE(m_Inst);\
	}\
private:\
	Type();\
	~Type();

 

*싱글턴 패턴의 static 변수 초기화 매크로

#define	DEFINITION_SINGLE(Type)	Type* Type::m_Inst = nullptr;

 

* 이렇게 싱글턴 매크로를 설정하면 싱글턴 패턴으로 구현해야 하는 클래스는

//NeedSingleton.h

class CNeedSingleton
{
	DECLARE_SINGLETON(CNeedSingleton)
}

이렇게 한 줄로 클래스가 싱글턴 패턴이 되도록 설정할 수 있다.

이 때, 세미콜론(;)은 사용하지 않는다.

 

* 싱글턴 패턴 클래스 내부에서 생성된 static Type* m_Inst 변수는 '정적 변수'이므로 클래스 내부에서 초기화가 불가능하므로

//NeedSingleton.cpp

DEFINITION_SINGLE(CNeedSingleton)

CNeedSingleton::CNeedSingleton()
{}

CNeedSingleton::~CNeedSingleton()
{}

이렇게 클래스 바깥 또는 클래스 .cpp 파일에서 별도로 DEFINITION_SINGLE 매크로를 통해 초기화 시켜주어야 한다.


* 유니코드-멀티바이트 문자집합에서 std::string 편하게 사용하기

//문자열
#include <string>
#ifdef _UNICODE
typedef std::wstring tstring
#else
typedef std::string tstring
#endif

또는

 

typedef std::basic_string<TCHAR> tstring

- 유니코드냐 멀티바이트냐에 따라 자동으로 char이나 wchar_t를 정해주는 매크로가 TCHAR이므로

비슷한 느낌으로 tstring을 만들어 사용하면 여러모로 편리할 듯.

- 아래 코드는

std::string == std::basic_string<char>

std::wstring == std::basic_string<wchar_t> 

이라는 점에서 착안하여 템플릿에 TCHAR을 집어넣은 것이다.

 

출처: https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=nine01223&logNo=220443106588 

 

(C++) string, wstring 그리고 tstring

윈도우 프로그래밍을 할 때 tstring을 자체적으로 선언해서 사용하면 대단히 편리합니다! 전형적인 윈도우 ...

blog.naver.com