COMS W4995 C++ Deep Dive for C Programmers

Index of 2025-9/code/05

Parent directory
Makefile
intarray1.cpp

Makefile

CC  = g++
CXX = g++

CFLAGS   = -g -Wall
CXXFLAGS = -g -Wall -std=c++14 -fno-elide-constructors

intarray1: intarray1.o

.PHONY: clean
clean:
	rm -f *~ a.out core *.o intarray1

.PHONY: all
all: clean default

intarray1.cpp

#include <string>
#include <iostream>

class IntArray {
public:
    IntArray() {
        sz  = 0;  // FIXME: use member initializer list
        cap = 1;
        a = new int[cap];
    }

    ~IntArray() {
        delete[] a;
    }

    IntArray(const IntArray&) = delete;
    IntArray& operator=(const IntArray&) = delete;

    // This is how we can explicitly request compiler-generated versions:
    // IntArray(const IntArray&) = default;
    // IntArray& operator=(const IntArray&) = default;

    int& operator[](int i) { return a[i]; }
    const int& operator[](int i) const { return a[i]; }

    size_t size() const { return sz; }
    size_t capacity() const { return cap; }

    void push_back(int x) {
        if (sz == cap) {
            int *a2 = new int[cap *= 2];  // FIXME: strong exception guarantee
            std::copy(a, a+sz, a2);
            delete[] a;
            a = a2;
        }
        a[sz++] = x;
    }

private:
    int *a;      // FIXME: is this the right order of declarations?
    size_t sz;
    size_t cap;
};

std::ostream& operator<<(std::ostream& os, const IntArray& ia) {
    for (size_t i = 0; i < ia.size(); i++) {
        os << ia[i] << " ";
    }
    os << "(cap=" << ia.capacity() << ")";
    return os;
}

int main() {
    using namespace std;

    IntArray ia;
    for (int i = 0; i < 20; i++) {
        ia.push_back(i);
        cout << ia << endl;
    }
}