Menu
CoddyTech

RAII 与作用域退出

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

Lua 5.4 只有在你明确要求时才会进行确定性清理:声明时带有 <close> 属性的局部变量,会在代码块结束时调用其值的 __close 元方法,即使错误导致代码展开退出也是如此。__gc 终结器会在垃圾回收器处理到该表时运行,因此依赖它的运行时机并不等同于 C++ RAII。C++ RAII 会在作用域退出时,通过对象销毁来释放资源,包括因异常展开而退出的情况;每个局部对象都如此,无需任何属性。所有权应由具有可靠析构函数的类型来管理。

Lua

local function trace()
  return setmetatable({}, {
    __close = function()
      print("closed")
    end,
  })
end
do
  local t <close> = trace()
  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";
}

分别跟踪每个程序。这些示例通过不同于任务的数据或操作来演示这个概念,不要认为源程序和目标程序的输出会相同。

challenge icon

挑战

简单

输入:非负的作用域数量。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自我测试

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

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

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