Menu
CoddyTech

RAII and Scope Exit

Lesson 30 of 48 in Coddy's C++ for C Developers course.

C cleanup requires explicit calls along every exit path. C++ automatic objects run destructors at scope exit, including exception unwinding. Put ownership in an object whose destructor releases it; this is RAII. Destruction timing differs from garbage collection and does not depend on memory pressure.

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
void cleanup(void){puts("closed");}
int main(void){
puts("work");cleanup();puts("done");
return 0;
}

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";
}

Trace each program independently. These examples demonstrate the concept with different operations or data from the task; source and target output are not assumed to match.

challenge icon

Challenge

Easy

Input: nonnegative number of scopes. Lease increments a referenced counter on construction and decrements it on destruction. Copying is forbidden. Driver repeatedly creates a nested lease and prints peak counter then final counter. Independent probes test nested destruction and exception unwinding.

Editable modules: Lease.cpp, Lease.hpp. Each required type has its own named header and implementation. Preserve all public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#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";
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C++ for C Developers

Practice on your own: Online C++ compiler