liveBook · Manning

Backing array

As explained in 100 C++ Mistakes and How to Avoid Them

A backing array is the dynamically managed array that provides storage for a resizable vector.

A backing array is the internal array that stores a resizable vector’s elements. When it fills, the vector allocates a larger array, copies the existing elements, and continues adding without user-written memory management. Repeated growth can be expensive, so reserve an estimated capacity when the required size is reasonably known. section 5.10

Mistake: choosing a fixed array for an unknown count

A fixed Person array requires a predetermined size and default-initialized slots, so unused positions can contain meaningless data. Replacing it with std::vector<Person> lets the program push actual people as needed; calling reserve(count) reduces avoidable backing-array reallocations while preserving correct behavior if the estimate is wrong. section 5.10

Listing 5.22 Static arrays force using a default constructor
struct Person {
    std::string name;
    int age;
    Person(const std::string& n, int a) : name(n), age(a) {}
    Person() : name("", 0) {}
};
 
int main() {
    Person people[3];                                       #1
    Person suzy("Susan", 25);
    people[0] = suzy;
    Person anna("Annette", 32);
    people[2] = anna;
    std::cout << people[1].name << '\n';
 
    int count = 5;  // assume this is computed
    Person* others = new Person[count];                     #2
    return 0;
}

Compare the fixed Person array, its forced default constructor, and the manually allocated array that motivates a safer vector-based design. section 5.10

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains allocation, copying, growth, and reserve, but stops short of implementation-level memory details.
Examples
Uses Person arrays, push_back, manual allocation, and reserve(count) to contrast fixed and resizable storage.
What it assumes
Assumes basic familiarity with C++ arrays, vectors, constructors, and dynamic allocation.
What you can do after
Apply it via std::vector, pushing elements dynamically and reserving estimated capacity to limit reallocations.
How it connects
Connects backing arrays to vectors, dynamic allocation, reallocation, reserve, element copying, and memory management.

Also explained in

Compare how 3 books explain backing array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.