查找初始化器列表中的哪个成员抛出异常 [英] Finding which member in an initializer list threw an exception
问题描述
假设我有一个类持有某些类型的成员。我知道 try-catch
阻塞初始化列表的语法如下
Lets say I have a class holding some members of some type. I know that the syntax for try-catch
blocks with initializer lists is as follows
template<int N>
struct Member
{
Member()
{
std::cout << "Default constructor of Member " << N << std::endl;
}
};
class A
{
Member<1> m1;
Member<2> m2;
// n members
public:
A() try
: m1()
, m2()
{
// constructor implementation
}
catch (std::exception const & e)
{
// ... cleanup
throw; // and rethrow
}
};
由于涉及初始化列表,我不能使用多个try catch块。 我如何知道哪个成员初始化引发了异常?
Since the initializer list is involved I can't use multiple try catch blocks. How can I tell which member initialization threw the exception?
推荐答案
/ p>
You can trace the initialization process
class A
{
Member<1> m1;
bool m1threw = true;
Member<2> m2;
bool m2threw = true;
// n members
public:
A() try
: m1()
, m1threw(false)
, m2()
, m2threw(false)
{
// constructor implementation
}
catch (std::exception const & e)
{
// ... cleanup
if (m1threw) {
//
}
else if (m2threw) {
}
throw; // and rethrow
}
};
注意类初始化仅在c ++ 11中有效。什么使你的例子更复杂是成员变量是默认构造。如果他们的构造函数接受了一个参数,那么这将是 构造的完美匹配跟踪器成语
Note In class initialization is only valid in c++11. What makes your example more complicated is that the member variables are default constructed. If their constructor accepted an argument, this would be a perfect match for the construction tracker idiom
我向成员提供了一个非默认构造函数,用于展示构造的示例 tracer idiom
I provided Member with a non default constructor to showcase an example of the construction tracer idiom
template<int N>
struct Member
{
Member(int some_arg)
{
std::cout << "Non default constructor of Meber " << N << std::endl;
}
};
class A
{
Member<1> m1;
Member<2> m2;
enum TrackerType { NONE, ONE, TWO };
public:
A(TrackerType tracker = NONE)
try // A constructor try block.
: m1((tracker = ONE, 1)) // Can throw std::exception
, m2((tracker = TWO, 1)) // Can throw std::exception
{
//TODO:
}
catch (std::exception const & e)
{
if (tracker == ONE) {
std::cout << "m1 threw: " << e.what() << std::endl;
}
else if (tracker == TWO) {
std::cout << "m2 threw: " << e.what() << std::endl;
}
throw;
}
};
本质上,这不需要额外的成员来实现跟踪,你可以看到,并且可以在11之前用c ++编译
Essentially this requires no extra members to achieve tracing as you can see and can compile with c++ prior to 11
这篇关于查找初始化器列表中的哪个成员抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!