What are the dangers of forward declarations?

前端 未结 9 1416
轻奢々
轻奢々 2021-02-01 16:58

I just had an interview. I was asked what is a \"forward declaration\". I was then asked if they were dangers associated with forward declarations.

I could not answer to

9条回答
  •  离开以前
    2021-02-01 17:10

    I came across an interesting snippet in the Google C++ Style Guide

    The danger they point to arises from implementing functions on incomplete types. Normally, this the compiler would throw an error, but because these are pointers, it can slip through the net.

    It can be difficult to determine whether a forward declaration or a full #include is needed. Replacing an #include with a forward declaration can silently change the meaning of code:

    // b.h:
    struct B {};
    struct D : B {};
    
    // good_user.cc:
    #include "b.h"
    void f(B*);
    void f(void*);
    void test(D* x) { f(x); }  // calls f(B*)
    

    If the #include was replaced with forward decls for B and D, test() would call f(void*).

提交回复
热议问题