Menu
CoddyTech

RAII 与作用域退出

Coddy 面向 PHP 开发者的 C++ 课程的第 30 课,共 48 课。

PHP 对象确实有析构函数:引用计数会在最后一个引用消失时立即调用 __destruct,例如函数返回时,或你对变量使用 unset 时。但 PHP 没有块作用域,因此在花括号内赋值的变量会一直存在,直到函数或脚本结束;被引用循环捕获的对象则要等到循环收集器处理。C++ RAII 会在作用域退出时将资源释放与对象销毁绑定起来,包括展开异常时。所有权应属于具有可靠析构函数的类型。

PHP

<?php
class Trace {
    public function __destruct() {
        echo "closed\n";
    }
}
{
    $t = new Trace();
    echo "work\n";
}
echo "done\n";

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 会读取标准输入,并直接调用 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自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 PHP 开发者的 C++中的所有课

自己练习: C++ 在线编译器