gpt4 book ai didi

C++:通过引用抛出派生类在捕获基类时不起作用

转载 作者:可可西里 更新时间:2023-11-01 15:22:37 35 4
gpt4 key购买 nike

我想用基类 Exception 抛出我自己的异常。有一个虚方法 print 将被子类覆盖。我只捕获类型 Exception& 并使用 print 来获取特定错误。问题是,一旦我抛出一个子类的引用,它就会被视为基类。

这是一个例子:

#include <iostream>
using namespace std;

class Exception
{
public:
virtual void print()
{
cout << "Exception" << endl;
}
};

class IllegalArgumentException : public Exception
{
public:
virtual void print()
{
cout << "IllegalArgumentException" << endl;
}
};

int main(int argc, char **argv)
{
try
{
IllegalArgumentException i;
Exception& ref = i;

cout << "ref.print: ";
ref.print();

throw ref;
}
catch(Exception& e)
{
cout << "catched: ";
e.print();
}
}

这个例子的输出是:

ref.print: IllegalArgumentException
catched: Exception

使用引用应该导致使用派生类的 print 方法。在 try block 中,引用确实使用了它。为什么捕获的 Exception& 不像 IllegalArgumentException 那样工作,我怎样才能得到这种行为?

下面的代码似乎做了它应该做的事情:

try
{
IllegalArgumentException i;
Exception* pointer = &i;

throw pointer;
}
catch(Exception* e)
{
cout << "pointer catched: ";
e->print();
}

但是指针在 try block 的范围之外是否可能变得无效?这样做会有风险,如果我在堆上分配内存来解决这个问题,我有责任在 catch block 内进行删除,这也不是很好。那么,您将如何解决这个问题?

最佳答案

throw 隐式复制,并因此切片。引用 C++11,§15.1/3:

A throw-expression initializes a temporary object, called the exception object, the type of which is determined by removing any top-level cv-qualifiers from the static type of the operand of throw and adjusting the type from “array of T” or “function returning T” to “pointer to T” or “pointer to function returning T”, respectively. The temporary is an lvalue and is used to initialize the variable named in the matching handler. If the type of the exception object would be an incomplete type or a pointer to an incomplete type other than (possibly cv-qualified) void the program is ill-formed. Except for these restrictions and the restrictions on type matching mentioned in 15.3, the operand of throw is treated exactly as a function argument in a call or the operand of a return statement.

我已经看到一些代码库通过抛出指向异常的指针而不是直接指向对象来解决这个问题,但就我个人而言,我只是首先重新考虑您是否“需要”这样做。

关于C++:通过引用抛出派生类在捕获基类时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9830220/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com