What are the dangers of forward declarations?

前端 未结 9 1425
轻奢々
轻奢々 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:22

    I'd say any danger is eclipsed by the gains. There are some though, mostly related to refactoring.

    • renaming classes impacts all forward-declarations. This of course also comes with includes, but the error is generated in a different place, so harder to spot.
    • moving classes from a namespace to another, coupled with using directives, can wreak havoc (mysterious errors, hard to spot and fix) - of course, the using directives are bad to start off with, but no code is perfect, right?*
    • templates - to forward declare templates (esp. user-defined ones) you'll need the signature, which leads to code duplication.

    Consider

    template class Y;
    int main()
    {
        Y<> * y;
    }
    
    //actual definition of the template
    class Z
    {  
    };
    template //vers 1.1, changed the default from int to Z
    class Y
    {};
    

    The class Z was changed afterwards as the default template argument, but the original forward declaration is still with int.

    *I've recently ran into this:

    Original:

    Definition:

    //3rd party code
    namespace A  
    {
       struct X {};
    }
    

    and forward declaration:

    //my code
    namespace A { struct X; }
    

    After refactoring:

    //3rd party code
    namespace B
    {
       struct X {};
    }
    namespace A
    {
       using ::B::X;
    }
    

    This obviously rendered my code invalid, but the error wasn't at the actual place and the fix was, to say the least, fishy.

提交回复
热议问题