liveBook · Manning

Push_back

As explained in Object-Oriented Software Design in C++

A standard C++ vector operation that appends an element to the container's end.

push_back() appends an element to the end of a C++ vector. The operation may do more than place one value: when the vector grows, it can allocate a longer internal array and copy existing elements into it. section 6.2.2

Appending dates

An Appointments wrapper calls dates.push_back(date) to append Date objects. Instrumentation shows that appending can invoke a copy constructor for the argument, allocate a new array, copy existing dates, destroy the old elements, and destroy temporary copies. section 6.2.2

Listing 6.11 (Program 6.7 SurpriseVector-1): Appointments.h (poor performance)
#include <vector>
#include "Date.h"

using namespace std;

class Appointments
{
public:
    vector<Date> get_dates() const { return dates; }

    Date at(const int index) const { return dates[index]; }
    void append(const Date date)   { dates.push_back(date); }

    void insert(const int index, const Date date)
    {
        dates.insert(dates.begin() + index, date);
    }

    void remove(const int index)
    {
        dates.erase(dates.begin() + index);
    }

private:
vector<Date> dates;       #1
};
#1 Private vector of Date objects

Inspect the Appointments wrapper to see push_back() used behind an append operation. section 6.2.2

How Object-Oriented Software Design in C++ covers it

How deep it goes
Explains copying, allocation, relocation, and destruction during growth, but does not develop broader vector-performance techniques.
Examples
Demonstrates append operations with Date objects and reports constructor and destructor calls through instrumentation.
What it assumes
Assumes basic C++ classes and vectors while illustrating copy construction and object destruction through a Date example.
What you can do after
Diagnose unexpected copying, allocation, and destruction when appending objects to a vector.
How it connects
Connects push_back() with vectors, copy constructors, destructors, dynamic arrays, and memory allocation.

Also explained in

Compare how 2 books explain push_back →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.