温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++不要在构造函数或析构函数中调用虚函数的原因是什么

发布时间:2021-09-14 15:25:15 来源:亿速云 阅读:156 作者:chen 栏目:大数据

这篇文章主要讲解了“C++不要在构造函数或析构函数中调用虚函数的原因是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++不要在构造函数或析构函数中调用虚函数的原因是什么”吧!



C++不要在构造函数或析构函数中调用虚函数的原因是什么


Reason(原因)

到目前为止,被调用的函数应该只属于构造对象本身,而不是可能存在于派生类中的某个覆盖函数。那样做非常难理解。最坏的情况,在构造函数或者析构函数中直接或间接调用一个没有实现的纯虚函数会导致没有定义的行为。


Example, bad(反面示例)
 
class Base {
public:
   virtual void f() = 0;   // not implemented
   virtual void g();       // implemented with Base version
   virtual void h();       // implemented with Base version
   virtual ~Base();        // implemented with Base version
};

class Derived : public Base {
public:
   void g() override;   // provide Derived implementation
   void h() final;      // provide Derived implementation

   Derived()
   {
       // BAD: attempt to call an unimplemented virtual function
       f();

       // BAD: will call Derived::g, not dispatch further virtually
       g();

       // GOOD: explicitly state intent to call only the visible version
       Derived::g();

       // ok, no qualification needed, h is final
       h();
   }
};
     

注意:调用一个特定的限定函数不是虚调用,即使这个函数是虚函数。

See also factory functions for how to achieve the effect of a call to a derived class function without risking undefined behavior.

参考工厂函数以便了解如何达成调用派生类功能的效果而不必承担引起未定义行为的风险。

Note(注意)

There is nothing inherently wrong with calling virtual functions from constructors and destructors. The semantics of such calls is type safe. However, experience shows that such calls are rarely needed, easily confuse maintainers, and become a source of errors when used by novices.

从构造函数和析构函数中调用虚函数并不是本身有什么错误。这种调用的语义是安全的。然而,经验表明这样的调用很少是必须的,很容易扰乱维护者,如果被新手使用会成为错误源。

Enforcement(实施建议)
  • Flag calls of virtual functions from constructors and destructors.

  • 提示来自构造函数或析构函数的虚函数调用。

感谢各位的阅读,以上就是“C++不要在构造函数或析构函数中调用虚函数的原因是什么”的内容了,经过本文的学习后,相信大家对C++不要在构造函数或析构函数中调用虚函数的原因是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI