기본 콘텐츠로 건너뛰기

delete this

[16] Freestore management, C++ FAQ Lite (내 맘대로 번역)
[16.15] Is it legal (and moral) for a member function to say delete this?
[16.15] 멤버함수에서 'delete this'가 올바른 구문인가?

As long as you're careful, it's OK for an object to commit suicide (delete this).
주의 깊게 사용한다면, 객체가 자살하는 구문(delete this)은 괜찮다.

Here's how I define "careful":
어떻게 "주의 깊게" 사용하냐면:

  1. You must be absolutely 100% positive sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).
    이 객체는 new연산자(new[]도 아니고, new 오버라이딩도 아니고, 스택에 있는 지역 객체도 아니고, 전역 객체도 아니고, 다른 객체의 멤버변수도 아닌 순수 그 자체 new연산자)로 만들어진다는 100% 확신이 있어야한다.
  2. You must be absolutely 100% positive sure that your member function will be the last member function invoked on this object.
    'delete this'를 호출한 멤버함수는 이 객체에서 호출한 가장 마지막 멤버함수라는 100% 확신이 있어야한다.
  3. You must be absolutely 100% positive sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members).
    'delete this' 구문 다음에 호출되는 이 객체의 다른 멤버함수는 이 객체의 그 어떠한 것이라도 건들이지 않는다는(다른 멤버 함수호출이나 멤버 변수에 접근까지 포함) 100% 확신이 있어야 한다.
  4. You must be absolutely 100% positive sure that no one even touches the this pointer itself after the delete this line. In other words, you must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it.
    'delete this' 다음에는 그 어떠한 것(심지어 'delete this'를 호출한 멤버함수까지도)도 'this'포인터를 참조하지 않는다는 100% 확신이 있어야한다. 예로, this포인터를 시험하거나, 다른 포인터와 비교하거나, NULL과 비교하거나, 포인터를 찍어보거나, 다른 형변환을 하는 등 이 모든 것이 금지 대상이다.

Naturally the usual caveats apply in cases where your this pointer is a pointer to a base class when you don't have a virtual destructor.
보통 이러한 주의사항은 'this'포인터가 가상 소멸자가 없는 부모 클래스의 포인터일 때 적용할 수 있다.


뭐, 한 마디로 '잘 쓴다면 상관 없는 구문이야~'라는 말이다. 문제는 '잘 쓴다면'이 꽤나 신경을 쓰게 만드니 문제다. 개인적인 취향으로 이러한 것은 머릿속 관리목록에 추가해야하는 녀석이기에 싫어한다. 정말이지 애초에 설계가 그렇게 만들어진 것을 어쩔 수 없어 떠안는 것이 아니라면 이런 것은 정말정말 쓰지 않았으면 하는 바이다.




덧글: 아무리 번역이 날림이라도 퍼가기 전에 알려줬으면 하는 바이다.

댓글

이 블로그의 인기 게시물

버즈 라이브 배터리 교체

나는 버즈 라이브(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 }