我是靠谱客的博主 靓丽毛豆,这篇文章主要介绍linux 构造函数 throw,构造函数抛出异常,现在分享给大家,希望可以做个参考。

#include

class bar

{

public:

bar()

{

std::cout << "bar() called" << std::endl;

}

~bar()

{

std::cout << "~bar() called" << std::endl;

}

};

class foo

{

public:

foo()

: b(new bar())

{

std::cout << "foo() called" << std::endl;

throw "throw something";

}

~foo()

{

delete b;

std::cout << "~foo() called" << std::endl;

}

private:

bar *b;

};

int main(void)

{

try {

std::cout << "heap: new foo" << std::endl;

foo *f = new foo();

} catch (const char *e) {

std::cout << "heap exception: " << e << std::endl;

}

try {

std::cout << "stack: foo" << std::endl;

foo f;

} catch (const char *e) {

std::cout << "stack exception: " << e << std::endl;

}

return 0;

}

输出:

heap: new foo

bar() called

foo() called

heap exception: throw something

stack: foo

bar() called

foo() called

stack exception: throw something

不会调用析构函数,因此,如果需要在构造函数中引发异常,则需要做很多事情(例如,清理吗?)。

最后

以上就是靓丽毛豆最近收集整理的关于linux 构造函数 throw,构造函数抛出异常的全部内容,更多相关linux内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(125)

评论列表共有 0 条评论

立即
投稿
返回
顶部