STL (cont.)
smart pointers & RAII
C/C++ wrapup
push 1 to 10 to std::vector
compute the sum
[gdb, performance, size/reserve, accumulate, list]
product of from 1 to 10?
#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;
}
lambda function: [](int x, int y) { return x * y; }
generic lambda (C++ 14, gcc 4.9+): use auto
read in names & phone numbers
query by name
Alice 206.555.1234
Bob 206.555.7890
C++ classes that mimic pointers
C++ 98: auto_ptr
- deprecated
C++ 11: unique_ptr
, shared_ptr
, weak_ptr
how to free resources?
example 1: HW1
example 2: kexec
easy to miss; complicated control flow; repeated free/delete
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
}
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
C explicit casts: (type)expr
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
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
guest lecture on Rust