小编Joh*_*ohn的帖子

C++ RAII无法正常工作?

我刚刚开始使用C++中的RAII并设置一个小测试用例.要么我的代码深感困惑,要么RAII无效!(我想这是前者).

如果我跑:

#include <exception>
#include <iostream>
class A {
public:
    A(int i) { i_ = i; std::cout << "A " << i_ << " constructed" << std::endl; }
    ~A() { std::cout << "A " << i_ << " destructed" << std::endl; }
private:
    int i_;
};

int main(void) {
    A a1(1);
    A a2(2);
    throw std::exception();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

除了注释外我得到:

A 1 constructed
A 2 constructed
A 2 destructed
A 1 destructed
Run Code Online (Sandbox Code Playgroud)

正如所料,但除了我得到:

A 1 constructed
A 2 constructed
terminate called …
Run Code Online (Sandbox Code Playgroud)

c++ exception raii

13
推荐指数
5
解决办法
1299
查看次数

标签 统计

c++ ×1

exception ×1

raii ×1