Why include a header and forward declare the class contained in the same cpp file?

前端 未结 4 549
难免孤独
难免孤独 2021-01-13 08:14

I\'ve been looking at the Fear SDK for my university project, but have noticed some code like so:

Foo.h

class Foo
{
    public:
        int iSomethin         


        
4条回答
  •  星月不相逢
    2021-01-13 09:04

    It's more than simply redundant, it's potentially problematic. Say Foo.h changes so Foo becomes a typedef to some particular instantiation of a generic, templatised equivalent - the kind of thing that can be anticipated as part of normal software evolution. Then Bar.cpp's "class X" will needlessly cause a compilation error ala:

    --- fwd.h ---
    template 
    class XT
    {
      public:
        int n_;
    };
    
    typedef XT X;
    
    --- fwd.cc ---
    #include "fwd.h"
    
    class X;
    
    int main()
    {
        X x;
        x.n_ = 0;
        return x.n_;
    }
    
    --- compilation attempt ---
    ~/dev  .../gcc/4.1.1/exec/bin/g++ fwd.cc -o fwd
    fwd.cc:3: error: using typedef-name 'X' after 'class'
    fwd.h:8: error: 'X' has a previous declaration here
    

    This is one reason I always recommend using dedicated forward-declaration headers ala , maintained with and included by the main header to ensure ongoing consistency. I never put "class X;" in an implementation file unless the class is defined in there too. Remember that the seeming benefits of "class X;" forward declarations is not so much that they avoid an #include, and more that the files they include can be large and in turn include a lot of other files: dedicated forward-declaration headers typically avoid the overwhelming majority of that anyway.

提交回复
热议问题