기본 콘텐츠로 건너뛰기

생성자, 소멸자에서 가상함수 불가

부모 클래스 생성자 또는 소멸자에서 가상함수를 호출하면 부모 클래스에 있는 가상함수를 호출한다. 이유는 간단하다. 자식클래스부분을 아직 생성하지 못했거나 이미 소멸했기 때문이다. 예를 들어보자.
#include <iostream>
using namespace std;

class CParent
{
public:
        CParent()
        {
                cout << __PRETTY_FUNCTION__ << endl;
                call_virtual_function();
        }

        virtual ~CParent()
        {
                cout << __PRETTY_FUNCTION__ << endl;
                call_virtual_function();
        }

        void call_virtual_function(void) const
        {
                cout << __PRETTY_FUNCTION__ << endl;
                virtual_function();
        }

        virtual void virtual_function(void) const
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }
};

class CChild : public CParent
{
public:
        CChild()
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }

        virtual ~CChild()
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }

        virtual void virtual_function(void) const
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }
};

int
main(int argc,char* argv[])
{
        cout << "Case1" << endl;
        CParent* p = new CChild;
        delete p;

        cout << "Case2" << endl;
        CChild* c = new CChild;
        delete c;

        return 0;
}
귀찮아서 gcc 확장인 __PRETTY_FUNCTION__을 사용했다. VC 같은데선 돌아가지 않는 소스다. 아름답게 컴파일을 하고 실행하면 다음과 같은 결과를 얻을 수 있다.
Case1
CParent::CParent()
void CParent::call_virtual_function() const
virtual void CParent::virtual_function() const
CChild::CChild()
virtual CChild::~CChild()
virtual CParent::~CParent()
void CParent::call_virtual_function() const
virtual void CParent::virtual_function() const
Case2
CParent::CParent()
void CParent::call_virtual_function() const
virtual void CParent::virtual_function() const
CChild::CChild()
virtual CChild::~CChild()
virtual CParent::~CParent()
void CParent::call_virtual_function() const
virtual void CParent::virtual_function() const
호출순서는 아래와 같다.
CParent() → CParent::call_virtual_function() → CParent::virtual_function() → CChild() → 객체 생성 완료!

~CChild() → ~CParent() → CParent::call_virtual_function() → CParent::virtual_function() → 객체 해체 완료!
아주 당연한 이치다. CParent가 call_virtual_function()을 통해 virtual_function()을 호출하려고 내부 virtual table을 뒤적였을 것이다. 그러나 virtual table에는 아직 CChild가 없기 때문에(CChild 생성자가 그 역을 한다) 당연히 CParent::virtual_function()을 호출했을 것이다.
반대도 마찬가지이다. CChild 소멸자가 virtual table에서 CChild를 삭제하였기 때문에 CParent::virtual_function()을 호출하는 것이다.

virtual table과 생성 관계를 증명하기 위해 한 가지 실험을 더 해보기로 하자.
#include <iostream>
using namespace std;

class CGrandParent
{
public:
        CGrandParent()
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }

        virtual ~CGrandParent()
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }

        void call_virtual_function(void) const
        {
                cout << __PRETTY_FUNCTION__ << endl;
                virtual_function();
        }

        virtual void virtual_function(void) const
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }
};

class CParent : public CGrandParent
{
public:
        CParent()
        {
                cout << __PRETTY_FUNCTION__ << endl;
                call_virtual_function();
        }

        virtual ~CParent()
        {
                cout << __PRETTY_FUNCTION__ << endl;
                call_virtual_function();
        }

        virtual void virtual_function(void) const
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }
};

class CChild : public CParent
{
public:
        CChild()
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }

        virtual ~CChild()
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }

        virtual void virtual_function(void) const
        {
                cout << __PRETTY_FUNCTION__ << endl;
        }
};

int
main(int argc,char* argv[])
{
        cout << "Case3" << endl;
        CGrandParent* g = new CChild;
        delete g;

        return 0;
}
좀 헷갈리지? CParent 기능 몇개를 CGrandParent로 옮기고 CParent가 CGrandParent를 상속 받았을 뿐이다. (이 예제에서 굳이 CChild는 필요 없는데...) 역시나 CParent()가 call_virtual_function()을 호출하도록 했다.

실행결과는 아래와 같다.
Case3
CGrandParent::CGrandParent()
CParent::CParent()
void CGrandParent::call_virtual_function() const
virtual void CParent::virtual_function() const
CChild::CChild()
virtual CChild::~CChild()
virtual CParent::~CParent()
void CGrandParent::call_virtual_function() const
virtual void CParent::virtual_function() const
virtual CGrandParent::~CGrandParent()
CParent()가 CGrandParent::call_virtual_function()을 호출하기 전에 CParent를 virtual table에 등록했으며, 따라서 CGrandParent::call_virtual_function()이 virtual_function()을 찾을 때 CParent::virtual_function()을 찾는다. 따라서 CParent::virtual_function()을 호출한다. 그러나 CChild는 virtual_table에 등록하지 않았기 때문에 CChild::virtual_function()을 호출하진 않는다. 반대도 마찬가지이다. 더 쓰면 손꾸락만 아프다.

이 문제 핵심은 clear(), destroy() 메서드 구현이다. 역시나 예를 들어보자.
#include <iostream>
using namespace std;

class CParent
{
public:
        CParent() : p(NULL)
        {
        }

        virtual ~CParent()
        {
                destory();
        }

protected:
        virtual void destory(void)
        {
                cout << __PRETTY_FUNCTION__ << endl;
                if ( p )
                {
                        delete p;
                        p = NULL;
                }
        }

protected:
        int* p;
};

class CChild : public CParent
{
public:
        CChild() : CParent(), p2(NULL)
        {
        }

        virtual ~CChild()
        {
                // do nothing
        }

protected:
        virtual void destory(void)
        {
                cout << __PRETTY_FUNCTION__ << endl;
                if ( p2 )
                {
                        delete p2;
                        p2 = NULL;
                }
                CParent::destory();
        }

protected:
        int* p2;
};

int
main(int,char**)
{
        cout << "Case4" << endl;
        CParent* p = new CChild;
        delete p;
        return 0;
}
컴파일해서 실행한 결과는 아래와 같다.
Case4
virtual void CParent::destory()
만약 CChild::p2를 할당한 객체라면 메모리가 좔좔 샐 것이다. 이걸 해결할만한 방법이... 갑자기 생각 안 나므로 나중에 포스팅 해야겠다.

댓글

이 블로그의 인기 게시물

버즈 라이브 배터리 교체

나는 버즈 라이브(SM-R180)가 좋은데, 평가가 별루였는지, 해당 스타일로 버즈를 더 이상 만들지 않고 있다. 아무튼, 오래 쓴 버즈 라이브 배터리가 슬슬 맛이 가기 시작해서, 블로그 를 참조하면서 분해 및 교체를 하였다. (진짜 쉬움) 요로코롬 위아래를 살짝 눌러주면 뚜껑이 벌어진다. 안쪽 플라스틱은 오른쪽은 분홍색, 왼쪽은 회색이다. 리본 케이블 살짝 들어내고, 기판을 떼어내면, 작은 나사가 있다. 나사를 풀고, 플라스틱을 걷어내면, 검은 양면 테이프로 고정된 CR1254 배터리가 보인다. 잘 쑤셔서(?) 꺼낸다. 새로운 CR1254 배터리를 넣는다. 음극이 아래로 가도록 하고, 분해의 역순으로 조립하면 된다. 조립할 때, 아까 풀었던 나사는 잊지 말고 꼭 조여준다. (까먹고 조립해서 다시 뜯고 조립함) 충전도 잘 되고, 소리도 잘 나는거 보면, 조립도 잘 된 것 같다. 이렇게 버즈 라이브의 수명을 강제로 늘렸다. 나중에 본체 배터리도 갈아야겠다.

ESP8266 + TM1637 WIFI 인터넷 시계 만들기

ESP8266 과 TM1637 으로 인터넷 시계 만들기 원래는 다이소에서 판매하는 5000원짜리 시계 뜯어서 만드려고 했는데, 시계를 뜯어보니, 자체 MCU를 통해 제어를 하고 있어 TM1637 로 구현하고 나중에 케이스를 만드는게 나을 것 같아서 아래와 같이 구현(chatGPT)했다. 30분마다 NTP 가져오기 WIFI가 끊기더라도 RTC 유지 WIFI가 끊기면 1분에 한 번씩 재접속 시도 버튼을 3초 누르면, AP 설정 모드 (88:88 표시) #include <ESP8266WiFi.h> #include <WiFiUdp.h> #include <TM1637Display.h> #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager #define CLK D5 // TM1637 CLK #define DIO D6 // TM1637 DIO #define CONFIG_BUTTON_PIN D7 // 설정 진입 버튼 TM1637Display display(CLK, DIO); // 시간 관련 변수 time_t currentEpochTime = 0; unsigned long lastNtpMillis = 0; unsigned long checkTermMillis = 1800000UL; // 30분마다 NTP 다시 받아옴 // Wi-Fi 재접속 관련 unsigned long lastWiFiReconnectAttempt = 0; const unsigned long wifiReconnectInterval = 60000; // 1분 // 버튼 관련 unsigned long buttonPressedTime = 0; bool buttonWasHeld = false; const unsigned long CONFIG_HOLD_TIME = 3000; // 3초 bool isInConfigMode = false; const char* ntpServer = ...

Windows 에서 절전을 깨우는 장치 찾기

참조:  https://www.reddit.com/r/computer/comments/wquswv/windows_11_pc_wakes_up_every_time_i_move_usb/ powercfg /devicequery wake_armed powercfg /deviceenablewake "[DEVICE]" # $PROFILE function Get-WakeArmedDevices { $devices = powercfg -devicequery wake_armed if ($devices) { $devices | ForEach-Object { $_.Trim() } } else { Write-Host "No devices are currently armed for wake events." } } function Set-EnableWakeOnDevice { param( [string]$deviceName ) sudo powercfg -deviceenablewake $deviceName } function Set-DisableWakeOnDevice { param( [string]$deviceName ) sudo powercfg -devicedisablewake $deviceName }