c++ - 私有(private)继承、友元和异常处理

标签 c++ inheritance exception-handling friend

当A类私有(private)继承自B类时,意味着B是A的私有(private)基类子对象。但对 friend 来说不是,对 friend 来说是公共(public)子对象。当有多个 catch 处理程序时,第一个匹配的处理程序(即,如果异常类型可以隐式转换为处理程序的参数类型)被调用。那么有人会向我解释为什么下面的代码不能像我预期的那样工作吗?此行为是标准有意为之还是 MSVC 错误?

class A
{
};
class B:A //private inheritance 
{
    friend void g();
}; 

void f()
{

    B b;
    //A* pa = &b; // error, conversion exists, but is inaccessible
    throw b;
}

void g()
{
    B b;
    A* pa = &b; //ok, private inheritance, but g() is B's friend so it is as though public
    try
    {
        f();
    }
    catch(A&)
    {
        //WHY ISN'T THIS HANDLER INVOKED?! B&->A& conversion exists in this function
    }
    catch(B&)
    {       
    }
}

int main()
{
    g();
}

附言这不是真正的代码,这是一个理论实验,也就是说,不要告诉我 friend 不好,组合优于私有(private)继承等。

提前致谢

最佳答案

不,标准不是这么说的。它说(C++0x):

A handler is a match for an exception object of type E if

— The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or

— the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or

— the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler by either or both of

    — a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes

    — a qualification conversion

— the handler is a pointer or pointer to member type and E is std::nullptr_t

基本原理:实现复杂。您可以将此视为转换发生在 throw 和 catch 之间的某处,而不是 g 本身。

关于c++ - 私有(private)继承、友元和异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3899563/

相关文章:

c++ - 推力 vector 距离计算

Python 继承 : Is it necessary to explicitly call the parents constructor and destructor?

c++ - 继承和存储静态类信息

python - 为什么 Python 中没有 @override 装饰器来帮助提高代码的可读性?

c# - ObjectContext 实例已被释放,不能再用于需要连接的操作

c++ - 从字符数组中消除重复项

c++ - C++ 中的静态成员 Qt 对象

c++ - 为什么我的代码给我一个分段/核心转储错误?

exception-handling - 如何处理@ControllerAdvice 中所有未处理的异常?

r - 在 tryCatch 中的警告之前处理错误