Menu
CoddyTech

RAII and Scope Exit

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

Luau has no destructors and no with statement. The garbage collector reclaims a table whenever it decides to, and Luau does not run a __gc metamethod on tables, so cleanup is an explicit call, usually placed after a pcall so it also runs when the work raises an error. C++ RAII ties resource release to object destruction at scope exit, including exception unwinding. Ownership belongs in a type with a reliable destructor.

Luau

local function withTrace(work)
    local ok, err = pcall(work)
    print("closed")
    if not ok then
        error(err, 0)
    end
end
withTrace(function()
    print("work")
end)
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";
}

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

Practice on your own: Online C++ compiler