The STL

The standard template library is a collection of memory safe objects that do what we did in the previous chapter for us. The STL stands for standard template library and it is called that because template code (generic programming) is a little funky in cpp, and it exists in a special library that is compiled with your program, rather then being compiled to a binary first and then linked like most other cpp libraries are.

std::string

std::string, is imported using #include <string>.

In C a string is defined as a char*, or as we learned a dynamic char array. std::string is just a wrapper around this allowing us to create memory safe cstring (synonym for char*) like things.

std::vector

std::vector is our dynamically allocated array, imported using #include <vector>.

It works exactly like a mix between the arraylist class in java, and the class we defined previously.

For example:

#include <iostream>
#include <vector>

int main() {
    for (;;) {
        int size;
        std::cin >> size;

        vector<int> arr(size);

        for (int i = 0; i < size; i++) {
            arr[i] = i;
        }

        for (int i = 0; i < size; i++) {
            std::cout << arr[i] << std::endl;
        }
    }
    return 0;
}

Smart Pointers

Smart pointers are classes for objects that follow raii, in order to automagically manage memory like we did previously.

They are imported using #include <memory>.

They consist of two main objects, the unique_ptr, and the shared_ptr.

The unique_ptr is a object that handles memory management using the raii pattern and is pretty much just that. Really doesn't have much special. If we remember the heap allocation of objects in the first chapter, a unique ptr does the exact same thing without having to worry about new or delete.

They look like this

// constructor
unique_ptr<obj> = make_unique<obj>();

// constructor with values
unique_ptr<obj> = make_unique<obj>(a);

The unique ptr is called a unique pointer because it is for use when you only have one reference to the heap (one thing pointing to the heap).

The shared_ptr is almost exactly the same as a unique_ptr, but also tracks the amount of copies and references to other pointers there are.

It is initialised the exact same way but using shared_ptr instead.

Please look at Microsoft Pointer Reference for more info.