递归函数异常处理的关键是立即 unwound 递归栈,可能导致内存泄露和程序崩溃。处理异常的方法包括:封装异常到本地变量、使用 raii 包装或使用 std::terminate() 终止函数。举个例子,可以使用封装异常的方式处理计算阶乘的递归函数中的异常:if (n

C++ 递归函数中异常处理
递归函数在处理异常情况时需要格外小心,因为一旦发生异常,递归栈会立即被 unwound,导致所有未处理的局部变量被销毁,可能导致意外的内存泄露和程序崩溃。
处理方法
有多种方法可以在递归函数中处理异常情况:
1. 封装异常 into 本地变量
// 函数可以抛出 std::runtime_error 异常
void recursive_function(int remaining_depth) {
if (remaining_depth <p><strong>2. 使用 RAII 包装</strong></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2823" title="C++14"><img
src="https://img.php.cn/upload/manual/001/431/639/6ac8b33c327c4749.png" alt="C++14" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="overflowclass">C++14</a>
<p class="overflowclass">C++14 对 C++11 的修正与增强版本,适合旧系统维护和较老工具链兼容。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>RAII(资源获取即初始化)包装可以自动在异常发生时释放资源。使用自定义 RAII 包装器,可以在递归函数的参数列表中获取指向资源的指针,并在退出范围时保证释放资源。</p><pre class="brush:cpp;toolbar:false;">// RAII 包装器,在析构时释放资源
struct ResourceWrapper {
ResourceWrapper() {
// 获取资源
}
~ResourceWrapper() {
// 释放资源
}
};
void recursive_function(int remaining_depth, ResourceWrapper& resources) {
if (remaining_depth <p><strong>3. 使用终止函数</strong></p><p>终止函数允许在异常发生时立即停止递归调用。可以通过在递归函数中调用 <code>std::terminate()</code> 函数来实现,这将 unwound 堆栈并终止程序。</p><pre class="brush:cpp;toolbar:false;">void recursive_function(int remaining_depth) {
if (remaining_depth <p><strong>实战案例</strong></p><p>考虑一个递归函数,用于计算数字的阶乘:</p><pre class="brush:cpp;toolbar:false;">int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
使用封装异常 into 本地变量的方法,可以如下处理异常:
int factorial(int n) {
if (n
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!







