Search code examples
c++smart-pointersforward-declaration

Smart Pointers, Forward Declaration, and C4150


So as part of a large hobby learning project I have implemented a mostly complete smart pointer implementation. It does practically every thing I ask of it, except for one minor detail that may prove to be a deal-breaker if I can't solve it. Contrived Example:

//Header1.h

#include <Header2.h>

class A
{
//Methods and such that involve class B in return type / arguments
};

//Header2.h

class A; //Forward declaration of A, needed because A includes Header2.h

class B
{
public:
    SmartPointer<A> Ptr;
};

The previous code, as you could guess, gives me warning C4150: deletion of pointer to incomplete type 'type'; no destructor called. I know why this is happening; in Header2.h, the smart pointer code includes a delete on a forward declared instance of A. If I could include Header1.h, no problem. I don't really wish to have to refactor at this point.

I have heard the boost smart pointer has this problem solved, somehow. Bringing in boost is not the intent of this project, as it is pretty much a hobby / learning project. So how does boost deal with this issue? How could I get the smart pointer to behave, in this instance, like a raw pointer? I have a few ideas, but I figured floating the question to SO could cull the list of ideas into a useful subset.

Forward declaring my thanks for helping me solve this one.


Solution

  • So how does boost deal with this issue?

    Boost deals with this issue by using checked_delete instead of delete inside the smart pointer class template, thus requiring the complete definition of A.