orl*_*rlp 5 c++ exception hierarchy c++11
我理解为了使用多重继承正确捕获异常,我需要使用虚拟继承.
我不一定主张有争议地使用多重继承,但我不想设计使其无法使用的系统.请不要分散这个问题来提倡或攻击使用多重继承.
所以假设我有以下基本异常类型:
class BaseException : public virtual std::exception {
public:
explicit BaseException(std::string msg)
: msg_storage(std::make_shared<std::string>(std::move(msg))) { }
virtual const char* what() const noexcept { return msg_storage->c_str(); }
private:
// shared_ptr to make copy constructor noexcept.
std::shared_ptr<std::string> msg_storage;
};
Run Code Online (Sandbox Code Playgroud)
BaseException?我的问题在于构造异常类型.理想情况下,每个异常只构造其父级,但由于虚拟继承,这是不可能的.一种解决方案是构建链中的每个父母:
struct A : public virtual BaseException {
explicit A(const std::string& msg) : BaseException(msg) { }
};
struct B : public virtual A {
explicit B(const std::string& msg, int code)
: BaseException(msg), A(msg), code_(code) { }
virtual int code() const { return code_; }
private:
int code_;
};
struct C : public virtual B {
explicit C(const std::string& msg, int code)
: BaseException(msg), A(msg), B(msg, code) { }
};
Run Code Online (Sandbox Code Playgroud)
但这似乎非常重复且容易出错.此外,这使得异常类型的构造者不可能在传递给他们各自的父母之前添加/改变他们的孩子传入的信息.