lec 14: smart pointers

today’s plan

STL (cont.)

smart pointers & RAII

C/C++ wrapup

self-exercise 1

push 1 to 10 to std::vector

compute the sum

[gdb, performance, size/reserve, accumulate, list]

product of from 1 to 10?

accumulate

#include <functional>
#include <iostream>
#include <numeric>
#include <vector>

int main() {
  std::vector<int> vec;
  for (int i = 1; i <= 10; ++i) vec.push_back(i);
  int prod = std::accumulate(vec.begin(), vec.end(), 1,
                             std::multiplies<int>());
  std::cout << prod << std::endl;
}

function object

lambda function: [](int x, int y) { return x * y; }

generic lambda (C++ 14, gcc 4.9+): use auto

self-exercise 2

read in names & phone numbers

query by name

Alice 206.555.1234
Bob   206.555.7890

phonebook.cc

smart pointers

C++ classes that mimic pointers

C++ 98: auto_ptr - deprecated

C++ 11: unique_ptr, shared_ptr, weak_ptr

others: boost, Chrome, WebKit

problem: resource management

how to free resources?

example 1: HW1

example 2: kexec

easy to miss; complicated control flow; repeated free/delete

unique_ptr

take ownership of a pointer

can be moved; cannot be copied

unique_ptr’s destructor invokes delete on the owned pointer

#include <memory>
#include <iostream>
int main() {
  std::unique_ptr<int> x(new int(5));
  // C++ 14: auto x = std::make_unique<int>(5);
  (*x)++;
  std::cout << *x << std::endl;
  // delete when the lifetime of x ends
}

RAII

Resource Acquisition Is Initialization

not limited to new/delete

template<
    class T,
    class Deleter = std::default_delete<T>
> class unique_ptr;
#include <memory>
#include <stdio.h>
int main() {
  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("foo.txt", "rb"), fclose);
  ...
}

decltype: typeof

type casting

  • C explicit casts: (type)expr

  • C++ explicit casts
    • const_cast<type>(expr)
    • static_cast<type>(expr)
    • reinterpret_cast<type>(expr)
    • dynamic_cast<type>(expr)

dynamic_cast: java-like run-time check

won’t work if run-time type information (RTTI) disabled

C/C++ projects

coding style: Google, Linux kernel, LLVM, Mozilla, clang-format

version control: git (CSE GitLab), mercurial, subversion

build system: GNU make, CMake, Ninja

analysis: cpplint, clang static analyzer, sparse

debugging: valgrind, AddressSanitizer

unit-testing: gtest

see you on Friday!

guest lecture on Rust