|
||||
|
Section 39:
|
[39.14] Why can't I put a forward-declared class in a std::vector<>?
Because the std::vector<> template needs to know the sizeof() its contained elements, plus the std::vector<> probably accesses members of the contained elements (such as the copy constructor, the destructor, etc.). For example, class Fred; // Okay: forward declaration class Barney { std::vector<Fred> x; // Error: the declaration of Fred is incomplete }; class Fred { Barney* y; };One solution to this problem is to change Barney so it uses a std::vector<> of Fred pointers rather than a std::vector<> of Fred objects: class Fred; // Okay: forward declaration class Barney { std::vector<Fred*> x; // Okay: Barney can use Fred pointers }; class Fred { Barney* y; };Another solution to this problem is to reverse the order of the classes so Fred is defined before Barney: class Barney; // Okay: forward declaration class Fred { Barney* y; // Okay: the first can point to an object of the second }; class Barney { std::vector<Fred> x; // Okay: Fred is fully defined at this point };Just remember this: Whenever you use a class as a template parameter, the declaration of that class must be complete and not simply forward declared. |
|||