C++-为什么C++在析构时调用的virtual函数出现异常?

小组事务管理 小组事务管理 主题:974 回复:1955

C++-为什么C++在析构时调用的virtual函数出现异常?

灵芸 发布于 2017-07-22 字数 0 浏览 1176 回复 2

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

支持 Markdown 语法,需要帮助?

评论(2

虐人心 2017-10-21 2 楼

Effective C++中说 不要在构造函数和析构函数中调用virtual函数
基类构造期间虚拟函数绝不会下降到继承类阶层,取而代之的是,对象的行为就像隶属基类类型一样,在基类构造期间,虚拟函数不是虚拟函数。在继承类对象的基类构造期间,对象的类型是基类而不是继承类

可以看看这里: Effective C++条款9:绝不在构造和析构函数过程中调用virtual函数

夜无邪 2017-10-19 1 楼

异常?如果你指的是exception的话,那么是不会的。C++可以在构造函数和析构函数里面调用virtual函数,只是其行为和其他地方调用virtual函数有所不同。
在C++03标准中说:
Member functions, including virtual functions (10.3), can be called during construction or destruction(12.6.2). When a virtual function is called directly or indirectly from a constructor (including from themem-initializer for a data member) or from a destructor, and the object to which the call applies is theobject under construction or destruction, the function called is the one defined in the constructor ordestructor’s own class or in one of its bases, but not a function overriding it in a class derived from the constructoror destructor’s class, or overriding it in one of the other base classes of the most derived object(1.8). If the virtual function call uses an explicit class member access (5.2.5) and the object-expressionrefers to the object under construction or destruction but its type is neither the constructor or destructor’sown class or one of its bases, the result of the call is undefined.