I’m trying to use forward declarations as much as I can to minimize compilation time. I noticed that when I forward declare a class that is using something like std::vector as a member object (example here):
class myTypeA
class A
{
A(){};
~A(){};
std::vector<myTypeA > getTypeA();
}
I get the following error:
microsoft visual studio 9.0\vc\include\vector(1112) : error C2036: 'myTypeA *' : unknown size
1> c:\program files\microsoft visual studio 9.0\vc\include\vector(1102) : while compiling class template member function 'bool std::vector<_Ty>::_Buy(unsigned int)'
1> with
1> [
1> _Ty=myTypeA
1> ]
1> d:\cpp\A.h(15) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
1> with
1> [
1> _Ty=myTypeA
1> ]
this is working fine when I use the #include “myTypeA.h”, why ?
This is because the compiler needs to know the size of the types to be stored in the vector. Without the full class definition it has no way of know this.
An alternative would be to store pointers to your forward-declared type – however you would need to manage the memory allocation and deallocation.
A third option would be to declare a
shared_ptrtype based on your forward declared type and store these in your vector.