How to instantiate a static vector of object?

Michael picture Michael · Sep 23, 2011 · Viewed 33.4k times · Source

I have a class A, which has a static vector of objects. The objects are of class B

class A {
  public:
    static void InstantiateVector();
  private:
    static vector<B> vector_of_B;
}

In function InstantiateVector()

for (i=0; i < 5; i++) {
  B b = B();
  vector<B>.push_back(b);
}

But I have compilation error using visual studio 2008: unresolved external symbol... Is it possible to instantiate static vector using above method? For object b to be created, some data has to be read from input file, and stored as member variables of b

Or it is not possible, and only simple static vector is possible? I read somewhere that to instantiate static vector, you must first define a const int a[] = {1,2,3}, and then copy a[] into vector

Answer

Chad picture Chad · Sep 23, 2011

You have to provide the definition of vector_of_b as follows:

// A.h
class A {
  public:
    static void InstantiateVector();
  private:
    static vector<B> vector_of_B;
};

// A.cpp
// defining it fixes the unresolved external:
vector<B> A::vector_of_B;

As a side note, your InstantiateVector() makes a lot of unnecessary copies that may (or may not) be optimized away.

vector_of_B.reserve(5);  // will prevent the need to reallocate the underlying
                         // buffer if you plan on storing 5 (and only 5) objects
for (i=0; i < 5; i++) {
  vector_of_B.push_back(B());
}

In fact, for this simple example where you are just default constructing B objects, the most concise way of doing this is simply to replace the loop all together with:

// default constructs 5 B objects into the vector
vector_of_B.resize(5);