gpt4 book ai didi

c++ - 查找初始化列表中的哪个成员抛出异常

转载 作者:太空狗 更新时间:2023-10-29 21:00:21 24 4
gpt4 key购买 nike

假设我有一个类(class),里面有一些成员。我知道带有初始化列表的 try-catch block 的语法如下

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 block 。 如何判断哪个成员初始化抛出了异常?

最佳答案

可以追溯初始化过程

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有效。使您的示例更复杂的是成员变量是默认构造的。如果他们的构造函数接受了一个参数,这将是 construction tracker idiom 的完美匹配。

我为 Member 提供了一个非默认构造函数来展示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;
}
};

基本上这不需要额外的成员来实现跟踪 as you can see并且可以用 11 之前的 c++ 编译

关于c++ - 查找初始化列表中的哪个成员抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22260567/

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