views:

1425

answers:

2

Hi!

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:

class myclass;
typedef boost::shared_ptr<myclass> pmyclass;
typedef std::list<pmyclass > myclasslist;

class myclass : public baseclass
{
private:        // private member declarations
        __fastcall myclass();

public:         // public member declarations
        __fastcall myclass(myclass *Parent)
            : mEntry(new myclass2())
          {
            this->mParent = Parent;
          }
        const myclass *mParent;
        myclasslist mChildren;
        boost::scoped_ptr<myclass2> mEntry;
};

so my question is: are there any drawbacks in this method? I recall some discussion on destructor issues with forward declaration but I did not get everything out of there.
or is there any other option to implement something like this?

Thanks.

EDIT: I found the discussion I was referring to: here

+2  A: 

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."

David Claridge
well, sorry for stupidity but I had read it before and my question here is:if it is defined right after declaration there should be no problem, right?
Andrew
Yes, well that's how I read it. Let's hope our compilers are standards-compliant :-)
David Claridge
+5  A: 

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.

Coincoin