【发布时间】:2012-01-06 16:13:14
【问题描述】:
斯科特迈耶斯说:
C++ 规定总是复制作为异常抛出的对象,并且复制由对象的复制构造函数执行。
但在我的代码中:
struct test
{
test() { cout << "constructor is called" << endl; }
test(const test&) { cout << "copy constructor is called" << endl; }
~test() { cout << "destructor is called" << endl; }
};
void fun()
{
throw test();
}
int main()
{
try {
fun();
}
catch (test& t1) { cout << "exception handler" << endl; }
}
我没有看到异常对象的复制构造函数被调用。
如果我将 catch 更改为按值接收异常对象,那么它是,但根据 Meyers 的引用,即使通过引用接收异常对象也应该被复制。
为什么不调用复制构造函数(即使通过引用执行异常处理)?
【问题讨论】:
-
问题是“哪个是错的:迈耶斯还是我的编译器?”不要仅仅因为你不理解问题而关闭它们。
标签: c++