3 回答
![?](http://img1.sycdn.imooc.com/533e4d510001c2ad02000200-100-100.jpg)
TA贡献1827条经验 获得超8个赞
是的,从失败的构造函数中引发异常是执行此操作的标准方法。阅读有关处理失败的构造函数的常见问题,以获取更多信息。拥有init()方法也可以,但是创建互斥对象的每个人都必须记住必须调用init()。我觉得这违反了RAII原则。
![?](http://img1.sycdn.imooc.com/5458502c00012d4a02200220-100-100.jpg)
TA贡献1895条经验 获得超3个赞
如果确实从构造函数引发异常,请记住,如果需要在构造函数初始化器列表中捕获该异常,则需要使用try / catch语法。
例如
func::func() : foo()
{
try {...}
catch (...) // will NOT catch exceptions thrown from foo constructor
{ ... }
}
与
func::func()
try : foo() {...}
catch (...) // will catch exceptions thrown from foo constructor
{ ... }
![?](http://img1.sycdn.imooc.com/54586453000163bd02200220-100-100.jpg)
TA贡献1852条经验 获得超7个赞
#include <iostream>
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
不会调用析构函数,因此,如果需要在构造函数中引发异常,则需要做很多事情(例如,清理吗?)。
- 3 回答
- 0 关注
- 490 浏览
添加回答
举报