Menu
CoddyTech

RAIIとスコープ終了

Coddyの「C#開発者のためのC++」コースのレッスン 30/48。

C#のIDisposableとusingスコープは、タイミングが非決定的なマネージドファイナライザーよりも、RAIIに近い仕組みです。C++のRAIIでは、スコープ終了時のオブジェクト破棄にリソースの解放が結び付いており、例外のスタック巻き戻し中も同様です。所有権は、信頼できるデストラクターを持つ型に持たせます。

C#

using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Trace:IDisposable{public void Dispose(){Console.WriteLine("closed");}}
static void Main() {
using(var t=new Trace()){Console.WriteLine("work");}Console.WriteLine("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";
}

各プログラムを個別にトレースしてください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソースとターゲットの出力が一致するとは限りません。

challenge icon

チャレンジ

簡単

入力:スコープの数(0以上)。Leaseは構築時に参照先のカウンターを増やし、破棄時に減らします。コピーは禁止されています。ドライバーは入れ子になったLeaseを繰り返し作成し、カウンターの最大値、次に最終値を出力します。独立したテストでは、入れ子の破棄と例外の巻き戻しを検証します。

編集可能なモジュール:Lease.cpp、Lease.hpp。各必須型には、それぞれ名前付きのヘッダーと実装があります。すべての公開シグネチャを維持してください。ロックされたmain.cppは標準入力を読み取り、APIを直接呼び出します。また、記載されている箇所では、公開APIの動作も独立して検証します。API内では出力せず、戻り値を返してください。整数の入力値と結果は符号付き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";
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C#開発者のためのC++のすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ