Menu
CoddyTech

RAII and Scope Exit

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

GDScript has no with statement and no destructor syntax. A RefCounted object is freed as soon as its last reference goes away, and its _notification receives NOTIFICATION_PREDELETE first, but a Node or plain Object lives until you call free() or queue_free(). C++ RAII ties resource release to object destruction at scope exit, for every type and also during exception unwinding. Ownership belongs in a type with a reliable destructor.

GDScript

extends Node

class Trace extends RefCounted:
    func _notification(what: int) -> void:
        if what == NOTIFICATION_PREDELETE:
            print("closed")

func work() -> void:
    var _trace := Trace.new()
    print("work")

func _ready() -> void:
    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";
}

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

Practice on your own: Online C++ compiler