前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.82:不要在构造函数或析构函数中调用虚函数

C++核心准则C.82:不要在构造函数或析构函数中调用虚函数

作者头像
面向对象思考
发布2020-03-25 16:22:08
7310
发布2020-03-25 16:22:08
举报

C.82: Don't call virtual functions in constructors and destructors

C.82:不要在构造函数或析构函数中调用虚函数

Reason(原因)

The function called will be that of the object constructed so far, rather than a possibly overriding function in a derived class. This can be most confusing. Worse, a direct or indirect call to an unimplemented pure virtual function from a constructor or destructor results in undefined behavior.

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

Example, bad(反面示例)

代码语言:javascript
复制
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();
    }
};

Note that calling a specific explicitly qualified function is not a virtual call even if the function is virtual.

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

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.
  • 提示来自构造函数或析构函数的虚函数调用。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c82-dont-call-virtual-functions-in-constructors-and-destructors


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档