C/C++ Arena

Step 1 of 5

unique_ptr

In C, every malloc needs exactly one free, and forgetting it (or doing it twice) is a bug. C++'s raw new and delete have the same problem. A smart pointer is a small object that owns a heap object and deletes it for you in its destructor. It's RAII applied to heap memory.

std::unique_ptr<T> (from <memory>) is the one to use by default. It has one owner, and it costs nothing extra at run time compared with a raw pointer.

#include <iostream>
#include <memory>
#include <string>
#include <utility>

struct Robot {
    std::string name;
    int battery;
    Robot(std::string n, int b) : name(n), battery(b) { std::cout << name << " built\n"; }
    ~Robot() { std::cout << name << " scrapped\n"; }
};

int main() {
    auto r = std::make_unique<Robot>("R2", 80);   // arguments go to Robot's constructor
    r->battery -= 30;                              // -> works like a raw pointer
    std::cout << (*r).name << " at " << r->battery << "%\n";
    {
        auto temp = std::make_unique<Robot>("C3", 100);
        std::cout << "inner block ends\n";
    }                                              // temp deletes its Robot here
    std::cout << "main ends\n";
}                                                  // r deletes its Robot here
R2 built
R2 at 50%
C3 built
inner block ends
C3 scrapped
main ends
R2 scrapped

How it works

Common mistakes

Your task

Create the object with make_unique and access it through the pointer.

Challenge 2

A unique_ptr can't be copied, only moved. Move a into b, check that a is now empty, then destroy the bomb early with reset(). The program prints a empty, b has B, then b empty.

Challenge 3

Write int tick_all(std::vector<std::unique_ptr<Bomb>>& bombs). It lowers every bomb's timer by 1. A bomb whose timer reaches 0 explodes: reset its pointer and count it. Skip slots that are already empty. Return how many exploded on this tick.

Next: Unique means unique