Menu
CoddyTech

RAII والخروج من النطاق

الدرس 30 من 48 في دورة C++ لمطوّري Rust على Coddy.

Rust

struct Trace;impl Drop for Trace {fn drop(&mut self){println!("closed");}}
fn main(){
{let _guard=Trace;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";
}

تتبّع كل برنامج على حدة. تعرض هذه الأمثلة المفهوم باستخدام عمليات أو بيانات تختلف عن تلك الموجودة في المهمة؛ ولا يُفترض أن يتطابق خرج المصدر والهدف.

challenge icon

التحدي

سهل

المدخل: عدد غير سالب من النطاقات. يزيد Lease عدّادًا مُشارًا إليه عند إنشائه وينقصه عند إتلافه. النسخ ممنوع. ينشئ برنامج التشغيل Lease متداخلًا مرارًا ويطبع قيمة ذروة العدّاد ثم قيمته النهائية. تختبر عمليات تحقق مستقلة الإتلاف المتداخل والتراجع عن الاستثناءات.

الوحدات القابلة للتحرير: Lease.cpp، Lease.hpp. لكل نوع مطلوب ترويسة وتنفيذ يحملان اسمه. حافظ على جميع التواقيع العامة. يقرأ main.cpp المقفل من stdin ويستدعي الواجهة البرمجية مباشرةً. كما يتحقق بصورة مستقلة من سلوك الواجهة البرمجية العامة حيثما ذُكر ذلك. أعد القيم بدلًا من الطباعة داخل الواجهة البرمجية. تلائم المدخلات والنتائج الصحيحة النطاق signed 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++ لمطوّري Rust

تدرّب بنفسك: مترجم C++ عبر الإنترنت