[英]C++ exception thrown inside constructor member initializer?
Consider the following situation: 请考虑以下情况:
struct X { ... };
struct Y
{
Y(...);
...
X x;
...
}
X f()
{
...
if (...)
throw E;
...
}
Y::Y(...) :
... ,
x(f()) ,
...
{
...
}
Is there any undefined behaviour here? 这里有未定义的行为吗? Are there any gotchas or potential problems with such a design when E is thrown? 抛出E时,这种设计是否有任何陷阱或潜在问题?
Update: 更新:
Y::x
may not be the only member variable of Y
, may not be the first member variable in the class, and may be initialized half way through the Y::Y
init list. Y::x
可能不是唯一的成员变量Y
,可能无法在班上第一个成员变量,并且可以通过初始化一半Y::Y
初始化列表。
Is there any undefined behaviour here? 这里有未定义的行为吗?
No. The construction of Y
is aborted. 号的建造Y
被中止。
Are there any gotchas or potential problems with such a design when E is thrown? 抛出E时,这种设计是否有任何陷阱或潜在问题?
No Y
is ever created, so there is no destructor to call. 不会创建任何Y
,因此没有要调用的析构函数。 Destructors for fully constructed elements, those declared before x
in the class body, will be called automatically (how would you otherwise know how far the initialization list you were when it throw). 用于完全构造的元素的析构x
(在类体内在x
之前声明的那些析构函数)将被自动调用(否则您将如何知道初始化列表在抛出时的距离)。 If you need to destroy anything, then you must catch the exception and destroy it yourself. 如果需要销毁任何东西,那么必须捕获异常并自己销毁它。 You cannot absorb the exception, you can rethrow it, throw a new exception, or do nothing which will result in the exception being rethrown anyway. 您无法吸收异常,可以将其重新抛出,抛出新的异常,或者什么也不做,这将导致异常被重新抛出。 For your particular use case, there shouldn't be anything to destroy since the constructor body is not going to be invoked at all. 对于您的特定用例,不应破坏任何东西,因为构造函数主体根本不会被调用。
When an exception is throwing during the construction of an object, the destructors of all fully constructed subobjects are called. 当在对象的构造过程中引发异常时,将调用所有完全构造的子对象的析构函数。 That is, assuming your type X
throwing an exception correctly cleans up any resources it may have allocated before the exception was thrown, there is no issue. 也就是说,假设您的类型X
抛出异常正确地清除了在抛出异常之前它可能已分配的所有资源,则没有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.