RAII와 스코프 종료
Coddy의 Swift 개발자를 위한 C++ 코스 레슨. 48개 중 30번째.
Swift는 자동 참조 계산을 통해 클래스 인스턴스를 해제합니다. 마지막 강한 참조가 사라지는 즉시 deinit이 실행됩니다. 이는 결정적이지만, 범위가 아니라 참조를 따릅니다. 또한 최적화 프로그램은 사용되지 않는 객체의 수명을 일찍 끝낼 수 있으므로, 특정 시점에 의존하는 코드는 withExtendedLifetime으로 객체의 수명을 고정하거나 defer를 사용합니다. C++의 RAII는 예외 처리 과정의 스택 해제를 포함해 범위가 끝날 때 객체가 소멸하면서 리소스가 해제되도록 합니다. 소유권은 신뢰할 수 있는 소멸자가 있는 형식에 두어야 합니다.
Swift
final class Trace {
deinit { print("closed") }
}
do {
let trace = Trace()
withExtendedLifetime(trace) { print("work") }
}
print("done")
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Trace {~Trace(){std::cout<<"closed\n";}};
int main(){
{Trace t;std::cout<<"work\n";}std::cout<<"done\n";
}
각 프로그램의 동작을 개별적으로 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 원본과 대상의 출력이 같다고 가정하지 마세요.
챌린지
쉬움입력: 음이 아닌 스코프 수. Lease는 생성될 때 참조된 카운터를 증가시키고 소멸될 때 감소시킵니다. 복사는 금지됩니다. 드라이버는 중첩된 Lease를 반복해서 생성하고 최댓값 카운터와 최종 카운터를 출력합니다. 독립적인 검사에서는 중첩된 소멸과 예외 전파 중 스택 풀기를 테스트합니다.
편집 가능한 모듈: Lease.cpp, Lease.hpp. 각 필수 타입은 고유한 이름의 헤더와 구현 파일을 가집니다. 모든 공개 시그니처를 그대로 유지하세요. 잠긴 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API의 동작도 독립적으로 확인합니다. API 내부에서 출력하지 말고 반환값을 사용하세요. 정수 입력과 결과는 signed int 범위에 들어가며, 별도로 명시되지 않는 한 텍스트는 ASCII입니다.
직접 해보기
#include <type_traits>
#include "Lease.hpp"
#include <iostream>
int main(){ static_assert(!std::is_copy_constructible<Lease>::value,"This owning type must not be copyable");
{int p=0;{Lease a(p);if(p!=1)return 21;{Lease b(p);if(p!=2)return 22;}if(p!=1)return 23;}if(p!=0)return 24;try{Lease c(p);throw 1;}catch(int){}if(p!=0)return 25;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n;in>>n;int count=0,peak=0;for(int i=0;i<n;++i){Lease a(count);{Lease b(count);peak=std::max(peak,count);}}std::cout<<peak<<" "<<count<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Swift 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러