Menu
CoddyTech

RAII and Scope Exit

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

Kotlin on the JVM reclaims memory through garbage collection, which promises nothing about when an object goes away, so it is no tool for releasing resources. The closer analogy to C++ RAII is use on an AutoCloseable, which calls close() when its block ends, even when the block throws. C++ RAII ties resource release to object destruction at scope exit, including exception unwinding, with no extra call at the use site. Ownership belongs in a type with a reliable destructor.

Kotlin

class Trace : AutoCloseable {
    override fun close() = println("closed")
}

fun main() {
    Trace().use { println("work") }
    println("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";
}

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 Kotlin Developers

Practice on your own: Online C++ compiler