C++ Class forward declaration drawbacks?

后端 未结 2 1928
半阙折子戏
半阙折子戏 2021-02-19 20:30

I want to use forward declaration of a class in my software, so I can have typedefs
and use them inside the class full declaration.

Smth like this:

         


        
相关标签:
2条回答
  • 2021-02-19 21:20

    The main drawback is everything. Forward declarations are a compromise to save compilation time and let you have cyclic dependencies between objects. However, the cost is you can only use the type as references and can't do anything with those references. That means, no inheritance, no passing it as a value, no using any nested type or typedef in that class, etc... Those are all big drawbacks.

    The specific destruction problem you are talking about is if you only forward declare a type and happen to only delete it in the module, the behavior is undefined and no error will be thrown.

    For instance:

    class A;
    
    struct C 
    {
        F(A* a)
        {
            delete a;  // OUCH!
        }
    }
    

    Microsoft C++ 2008 won't call any destructor and throw the following warning:

    warning C4150: deletion of pointer to incomplete type 'A'; no destructor called
                 : see declaration of 'A'
    

    So you have to stay alert, which should not be a problem if you are treating warnings as errors.

    0 讨论(0)
  • 2021-02-19 21:35

    From the C++ standard:

    5.3.5/5:

    "If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined."

    0 讨论(0)
提交回复
热议问题