Skip to content
Snippets Groups Projects
frames.tex 66 KiB
Newer Older
Francesco Giacomini's avatar
Francesco Giacomini committed

Francesco Giacomini's avatar
Francesco Giacomini committed
%\includeonlyframes{current}
Francesco Giacomini's avatar
Francesco Giacomini committed

\begin{frame}
   \begin{tikzpicture}[remember picture,overlay]
     \node at ([yshift=1.5cm]current page.south) {\tiny\url{https://baltig.infn.it/giaco/cpp-memory-esc17}};
     \node at ([yshift=1cm]current page.south) {\includegraphics[height=.5cm]{by-sa}};
   \end{tikzpicture}
   \titlepage
Francesco Giacomini's avatar
Francesco Giacomini committed
\end{frame}

\begin{frame}{Outline}
  \tableofcontents
  % You might wish to add the option [pausesections]
\end{frame}

\section{Introduction}

\begin{frame}{What is C++}
  C++ is a complex and large programming language (and library)
  \begin{itemize}[<+->]
    \item strongly and statically typed
    \item general-purpose
    \item multi-paradigm
    \item good from low-level programming to high-level abstractions
    \item efficient (\textit{``you don't pay for what you don't use''})
    \item standard
  \end{itemize}

  \uncover<+->{The following material just scratches the surface}
\end{frame}

\begin{frame}{Where to go next}
  \begin{itemize}
    \item Start from
      \begin{itemize}
      \item \url{https://isocpp.org/}
      \item \url{https://en.cppreference.com/}
      \item \url{https://github.com/isocpp/CppCoreGuidelines}
      \end{itemize}
    \item Main C++ conferences
      \begin{itemize}
      \item \url{https://github.com/cppcon}, \url{https://youtube.com/cppcon}
      \item \url{https://github.com/boostcon}, \url{https://youtube.com/boostcon}
      \end{itemize}
    \item Standard Committee papers
    \begin{itemize}
    \item \url{http://www.open-std.org/jtc1/sc22/wg21/docs/papers/}
    \end{itemize}
  \end{itemize}
\end{frame}

\begin{frame}{C++ timeline}
  \includegraphics[width=\textwidth]{wg21-timeline-2017-07b.png}

  \pause
  \textit{``Modern C++ feels like a new language''}
\end{frame}

\begin{frame}{Standards}
  Working drafts, almost the same as the final published document
  \begin{description}
    \item [C++03] \url{http://wg21.link/n1905}
    \item [C++11] \url{http://wg21.link/n3242}
    \item [C++14] \url{http://wg21.link/n4296}
    \item [C++17] \url{http://wg21.link/n4659}
  \end{description}

  For the \LaTeX sources see \url{https://github.com/cplusplus/draft}
\end{frame}

\begin{frame}{Compilers}
  \begin{itemize}
  \item The ESC machines provide gcc 7.2 and clang 5.0
  \item You can also edit and try your code online with multiple compilers at
    \begin{itemize}
    \item \url{http://gcc.godbolt.org/}
    \item \url{http://coliru.stacked-crooked.com/}
    \end{itemize}
  \end{itemize}
\end{frame}

\section{Type deduction}

\begin{frame}[fragile]{\texttt{auto}}
  Let the compiler deduce the type of a variable from the initializer

Francesco Giacomini's avatar
Francesco Giacomini committed
  \begin{codeblock}
\uncover<1->{auto i = 0;                // int
Francesco Giacomini's avatar
Francesco Giacomini committed
auto u = 0U;               // unsigned int
auto p = &i;               // int*
auto d = 1.;               // double
auto c = 'a';              // char
Francesco Giacomini's avatar
Francesco Giacomini committed
auto s = "a";              // char const*}
\uncover<2->{auto t = std::string\{"a"\}; // std::string
Francesco Giacomini's avatar
Francesco Giacomini committed
std::vector<std::string> v;
Francesco Giacomini's avatar
Francesco Giacomini committed
auto it = std::begin(v);   // std::vector<std::string>::iterator}
\uncover<3->{using std::literals::chrono\_literals;
auto u = 1234us;           // std::chrono::microseconds}
\uncover<4->{auto e;                    // error}\end{codeblock}
Francesco Giacomini's avatar
Francesco Giacomini committed
\end{frame}

\begin{frame}[fragile]{\texttt{auto} and references}

  \begin{itemize}
  \item \texttt{auto} never deduces a reference
  \item if needed, \code{\&} must be added explicitly
  \end{itemize}

\begin{codeblock}
T v;

auto  v1 = v;     // T  -- v1 is a copy of v
auto\& v2 = v;     // T\& -- v2 is an alias of v
\alert{auto  v3 = v2;    // T  -- v2 is a copy of v}\end{codeblock}

\end{frame}

\begin{frame}[fragile]{\code{auto} and \code{const}}

  \begin{itemize}
  \item \code{auto} makes a mutable copy
  \item \code{auto const} (or \code{const auto}) makes a non-mutable copy
  \item \code{auto\&} preserves \code{const}-ness
  \end{itemize}

  \begin{codeblock}
T v;

auto        v1 = v; // T        -- v1 is a mutable copy of v
auto const  v2 = v; // T const  -- v2 is a non-mutable copy of v
auto\&       v3 = v; // \alert{T\&}       -- v3 is a \alert{mutable} alias of v
auto const\& v4 = v; // T const\& -- v4 is a non-mutable alias of v\end{codeblock}

  \begin{codeblock}
T const v;

auto        v1 = v; // T        -- v1 is a mutable copy of v
auto const  v2 = v; // T const  -- v2 is a non-mutable copy of v
auto\&       v3 = v; // \alert{T const\&} -- v3 is a \alert{non-mutable} alias of v
auto const\& v4 = v; // T const\& -- v4 is a non-mutable alias of v\end{codeblock}

\end{frame}

\begin{frame}[fragile]{How to check the deduced type?}
  \begin{itemize}
  \item Trick by S. Meyers
    \begin{codeblock}{
template<typename T> struct D;

auto k = 0U;
D<decltype(k)> d; // error: aggregate 'D<\alert{unsigned int}> d'...

auto const o = 0.;
D<decltype(o)> d; // error: aggregate 'D<\alert{const double}> d'...

auto const\& f = 0.f;
D<decltype(f)> d; // error: aggregate 'D<\alert{const float\&}> td'...

auto s = "hello";
D<decltype(s)> d; // error: aggregate 'D<\alert{const char*}> d'...

auto\& t = "hello";
D<decltype(t)> d; // error: aggregate 'D<\alert{const char (\&)[6]}> d'...}\end{codeblock}

  \item \code{decltype} returns the type of an expression
    \begin{itemize}
    \item at compile time
    \end{itemize}
  \end{itemize}
\end{frame}

\section{Function, function object, lambda}

\begin{frame}[fragile]{Functions}

  \begin{itemize}
  \item A function associates a sequence of statements (the function
    \textit{body}) with a name and a list of zero or more parameters

  \begin{codeblock}
\alt<1>{std::string}{\alert{auto       }} cat(std::string const\& s, int i)
\{
  return s + '-' + std::to\_string(i);
\}

// cat(std::string\{"XYZ"\}, 5) returns std::string\{"XYZ-5"\}\end{codeblock}

  \item A function may return a value
  \item A function returning a \code{bool} is called a \textit{predicate}
    \begin{codeblock}
bool less(int n, int m) \{ return n < m; \}\end{codeblock}

  \item Multiple functions can have the same name $\rightarrow$
    \textit{overloading}
    \begin{itemize}
    \item different parameter lists
    \end{itemize}
  \end{itemize}

  \pause
\end{frame}

\begin{frame}{STL Algorithms}

  \begin{itemize}[<1->]
  \item Generic functions that operate on \alert{ranges} of objects
  \item Implemented as function templates
  \end{itemize}

  \pause

  \begin{description}[<+->]
    \item[Non-modifying] \code{all\_of any\_of for\_each
      count count\_if mismatch equal find find\_if adjacent\_find search ...}
    \item[Modifying] \code{copy fill generate transform remove
      replace swap reverse rotate shuffle sample unique ...}
    \item[Partitioning] \code{partition stable\_partition ...}
    \item[Sorting] \code{sort partial\_sort nth\_element ... }
    \item[Set] \code{set\_union set\_intersection set\_difference
      ...}
    \item[Min/Max] \code{min max minmax lexicographical\_compare
      clamp ...}
    \item[Numeric] \code{iota accumulate inner\_product partial\_sum
      adjacent\_difference ...}
  \end{description}
\end{frame}

\begin{frame}{Range}

  \begin{itemize}
  \item A range is defined by a pair of \alert{iterators}
    [\textit{first}, \textit{last}), with \textit{last} referring to one
    past the last element in the range
    \begin{itemize}
    \item the range is \textit{half-open}
    \item \textit{first} == \textit{last} means the range is empty
    \item \textit{last} can be used to return failure
    \end{itemize}
  \item An \alert{iterator} is a generalization of a pointer
    \begin{itemize}
    \item it supports the same operations, possibly through
      overloaded operators
    \item certainly \code{* ++ -> == !=}, maybe \code{-{}- + - += -= <}
    \end{itemize}
  \item Ranges are typically obtained from containers calling specific
    methods
  \end{itemize}

\end{frame}

\begin{frame}[fragile]{Range \insertcontinuationtext}

  \begin{tikzpicture}
    [anchor=south west]
    \visible<1->{\node at (0,0) [memory] {};}
    \visible<1->{\node at (0,0) [word anchor,label={90:{\tiny\tt 0x0000}}] {};}
    \visible<1->{\node at (.9\textwidth-.25cm,0) [word anchor,label={90:{\tiny\tt 0xffff}}] {};}

    \visible<1->{\node at (3.9,-0.1) [
        rectangle,
        fill=green!10!white,
        draw=black!40,
        minimum width=3.2cm,
        minimum height=0.7cm,
        label=270:{\scriptsize\tt a},
      ] {};
    }
    \visible<1->{\node (a0) at (4,0) [word] {\scriptsize\tt\alert<5>{123}};}
    \visible<1->{\node (a1) at (5,0) [word] {\scriptsize\tt\alert<8>{456}};}
    \visible<1->{\node (a2) at (6,0) [word] {\scriptsize\tt\alert<11>{789}};}
    \visible<1->{\node (a3) at (7,0) [phantom word] {};}
    \visible<1->{\node at (4,0) [word anchor,label={90:{\tiny\tt 0xab00}}] {};}
    \visible<1->{\node at (5,0) [word anchor,label={90:{\tiny\tt 0xab04}}] {};}
    \visible<1->{\node at (6,0) [word anchor, label={90:{\tiny\tt 0xab08}}] {};}
    \visible<1->{\node at (7,0) [word anchor, label={90:{\tiny\tt0xab0c}}] {};}
    \visible<2->{\node (first) at (4,-1.5) [word, label={270:{\scriptsize\tt first}}] {};}
    \visible<3->{\node (last) at (7,-1.5) [word, label={270:{\scriptsize\tt last}}] {};}
    \visible<2-5>{\draw[->] (first.north) -- (a0.south);}
    \visible<3->{\draw[->] (last.north) --  (a3.south);}
    \visible<6-8>{\draw[->] (first.north) -- (a1.south);}
    \visible<9-11>{\draw[->] (first.north) -- (a2.south);}
    \visible<12->{\draw[->] (first.north) -- (a3.south);}

  \end{tikzpicture}

  \begin{codeblock}
\uncover<1->{std::array<int,3> a = \{123, 456, 789\};}
\uncover<2->{\alert<2>{auto first = a.begin();}       // or std::begin(a)}
Francesco Giacomini's avatar
Francesco Giacomini committed
\uncover<3->{\alert<3>{auto \only<14->{\alert{const }}last = a.end();}\only<-13>{      }    // or std::end(a)}
Francesco Giacomini's avatar
Francesco Giacomini committed
\uncover<4->{while (\alert<4,7,10,13>{first != last}) \{
  ... \alert<5,8,11>{*first} ...;
  \alert<6,9,12>{++first};
\}}\end{codeblock}

  \begin{itemize}[<15->]
  \item \code{std::array<T>::iterator} models the \textit{RandomAccessIterator} concept
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{Generic programming}

  \begin{itemize}[<+->]
  \item A style of programming in which \alert{algorithms} are written
    in terms of \alert{concepts}
  \item A concept is a set of requirements that a type needs to satisfy
    \begin{itemize}[<.->]
    \item e.g. supported expressions, nested typedefs, memory layout, \ldots
    \end{itemize}
  \end{itemize}

  \begin{codeblock}<+->
template <class Iterator, class T>
Iterator
find(Iterator first, Iterator last, const T\& value)
\{
  for (; first \alert{!=} last; \alert{++}first)
    if (\alert{*}first \alert{==} value)
      break;
  return first;
\}\end{codeblock}

\end{frame}

\begin{frame}[fragile]{Range \insertcontinuationtext}

  \begin{tikzpicture}
    [anchor=south west]
    \visible<1->{\node at (0,0) [memory] {};}
    \visible<1->{\node at (0,0) [word anchor,label={90:{\tiny\tt 0x0000}}] {};}
    \visible<1->{\node at (.9\textwidth-.25cm,0) [word anchor,label={90:{\tiny\tt 0xffff}}] {};}

    \visible<1->{\node (l) at (0.9,-0.1) [
        rectangle,
        fill=green!10!white,
        draw=black!40,
        minimum width=1.2cm,
        minimum height=0.7cm,
        label=270:{\scriptsize\tt l},
      ] {};
    }
    \visible<1->{\node (a0) at (3.5,0) [word] {\scriptsize\tt\alert<5>{123}};}
    \visible<1->{\node (a1) at (6.5,0) [word] {\scriptsize\tt\alert<8>{456}};}
    \visible<1->{\node (a2) at (5  ,0) [word] {\scriptsize\tt\alert<11>{789}};}
    \visible<1->{\node (a3) at (8  ,0) [phantom word,draw=black,densely dotted] {};}
    \visible<1->{\node (c0) at (3.5,0) [word anchor,label={90:{\tiny\tt 0xab00}}] {};}
    \visible<1->{\node (c1) at (6.5,0) [word anchor,label={90:{\tiny\tt 0xad08}}] {};}
    \visible<1->{\node (c2) at (5,0) [word anchor, label={90:{\tiny\tt 0xac04}}] {};}
    \visible<1->{\node (c3) at (8,0) [word anchor, label={90:{\tiny\tt0xae0c}}] {};}
    \visible<1->{\draw[Circle-Stealth] (l.east) .. controls +(1,1) .. (c0.north);}
    \visible<1->{\draw[Circle-Stealth] (a0.east) .. controls +(1,1.5) .. (c1.north);}
    \visible<1->{\draw[Circle-Stealth] (a1.east) .. controls +(-1,1) .. (c2.north);}
    \visible<1->{\draw[Circle-Stealth] (a2.east) .. controls +(1,1.5) .. (c3.north);}
    %    \visible<1->{\node at (3,0) [word anchor,label={90:{\tiny\tt 0xab00}}] {};}
    \visible<2->{\node (first) at (3.5,-1.5) [word, label={270:{\scriptsize\tt first}}] {};}
    \visible<3->{\node (last) at (8,-1.5) [word, label={270:{\scriptsize\tt last}}] {};}
    \visible<2-5>{\draw[->] (first.north) -- (a0.south);}
    \visible<3->{\draw[->] (last.north) --  (a3.south);}
    \visible<6-8>{\draw[->] (first.north) -- (a1.south);}
    \visible<9-11>{\draw[->] (first.north) -- (a2.south);}
    \visible<12->{\draw[->] (first.north) -- (a3.south);}

  \end{tikzpicture}

  \begin{codeblock}
\uncover<1->{std::forward\_list<int> l = \{123, 456, 789\};}
\uncover<2->{\alert<2>{auto first = l.begin();}}
\uncover<3->{\alert<3>{auto const last = l.end();}}
\uncover<4->{while (\alert<4,7,10,13>{first != last}) \{
  ... \alert<5,8,11>{*first} ...;
  \alert<6,9,12>{++first};
\}}\end{codeblock}

  \begin{itemize}[<14->]
  \item \code{std::forward\_list<T>::iterators} models the \textit{ForwardIterator} concept
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{Algorithms and ranges}

  \begin{itemize}
  \item Examples
    \begin{codeblock}
Francesco Giacomini's avatar
Francesco Giacomini committed
std::vector<int> v = \{ 2, 5, 4, 0, 1 \};
Francesco Giacomini's avatar
Francesco Giacomini committed

// sort the first half of the vector in ascending order
std::sort(std::begin(v), std::begin(v) + v.size() / 2);

// sum up the vector elements, initializing the sum to 0
auto s = std::accumulate(std::begin(v), std::end(v), 0);

// append the partial sums of the vector elements into a list
std::list<int> l;
std::partial\_sum(std::begin(v), std::end(v), std::back\_inserter(l));

// find the first element with value 4
auto it = std::find(std::begin(v), std::end(v), 4);
    \end{codeblock}

  \item Some algorithms are customizable passing a function
    \begin{codeblock}
Francesco Giacomini's avatar
Francesco Giacomini committed
auto s = accumulate(v.begin(), v.end(), std::string\{"X"\}, \alert{cat});
assert(s == "X-2-5-4-0-1");\end{codeblock}
Francesco Giacomini's avatar
Francesco Giacomini committed
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{Function objects}

  A mechanism to define \textit{something-callable-like-a-function}
  \begin{itemize}
  \item<4-> A class with an \texttt{operator()}
  \end{itemize}

  \begin{columns}[t]

    \begin{column}{.5\textwidth}

      \begin{codeblock}<2->{
\invisible{struct Cat}
auto \alert<2,4>{cat}(
  string const& s, int i
) \{
  return s + '-' + to\_string(i);
\}



auto s = \alert<2>{cat(}"XY", 5\alert<2>{)}; // XY-5

\uncover<3->{vector<int> v\{2,3,5\};
auto s = accumulate(
    begin(v), end(v),
    string\{"XY"\}, \alert<3>{cat}
); // XY-2-3-5}}\end{codeblock}

    \end{column}

    \begin{column}{.5\textwidth}

      \begin{codeblock}<4->{
\alert<4>{struct Cat \{}
 auto \alert<4>{operator()} (
  string const& s, int i
 ) \alert<4>{const} \{
  return s + '-' + to\_string(i);
 \}
\alert<4>{\};}

\uncover<5->{Cat \alert<-6>{cat}\only<5>{\{\}};}
\uncover<7->{auto s = \alt<7-8>{\alert<7>{cat(}}{\alert<9>{Cat\{\}}(}"XY", 5\alert<7>{)}; // XY-5}

\uncover<8->{vector<int> v\{2,3,5\};
auto s = accumulate(
    begin(v), end(v),
    string\{"XY"\}, \alt<8-9>{\alert<8>{cat}}{\alert<10>{Cat\{\}}}
); // XY-2-3-5}}\end{codeblock}

      \uncover<8-10>{}
    \end{column}
  \end{columns}
\end{frame}

\begin{frame}[fragile]{Function objects}
  A function object, being the instance of a class, can have state
  \begin{codeblock}<2->{
class CatWithState \{
  \alert<2>{char c\_;}
 public:
  \alert<2>{explicit CatWithState(char c) : c\_\{c\} \{\}}
  auto operator()(string const& s, int i) const \{
    return s + c\_ + to\_string(i);
  \}
\};

\uncover<3->{CatWithState cat1\{'-'\};
auto s1 = \alt<-5>{cat1}{\alert<6>{CatWithState\{'-'\}}}("XY", 5); // XY-5}

\uncover<4->{CatWithState cat2\{'+'\};
auto s2 = \alt<-5>{cat2}{\alert<6>{CatWithState\{'+'\}}}("XY", 5); // XY+5}

\uncover<5->{vector<int> v\{2,3,5\};
auto s3 = accumulate(\ldots, \alt<-5>{cat1}{\alert<6>{CatWithState\{'-'\}}}); // XY-2-3-5
auto s4 = accumulate(\ldots, \alt<-5>{cat2}{\alert<6>{CatWithState\{'+'\}}}); // XY+2+3+5}}\end{codeblock}

  \uncover<6>{}

\end{frame}

\begin{frame}[fragile]{Function objects \insertcontinuationtext}
  An example from the standard library

  \begin{codeblock}
#include <random>

// random bit generator (mersenne twister)
std::mt19937 gen;

// generate N 32-bit unsigned integer numbers
for (int n = 0; n != N; ++n) \{
  std::cout <{}< \alert{gen()} <{}< '\\n';
\}

// generate N floats distributed normally (mean: 0., stddev: 1.)
std::normal\_distribution<float> dist;
for (int n = 0; n != N; ++n) \{
  std::cout <{}< \alert{dist(gen)} <{}< '\\n';
\}

// generate N ints distributed uniformly between 1 and 6 included
std::uniform\_int\_distribution<> roll\_dice(1, 6);
for (int n = 0; n != N; ++n) \{
  std::cout <{}< \alert{roll\_dice(gen)} <{}< '\\n';
\}\end{codeblock}

\end{frame}

\begin{frame}[fragile]{Lambda expression}

  \begin{itemize}
  \item A concise way to create an unnamed function object
  \item Useful to pass actions/callbacks to algorithms, threads, frameworks,
    \ldots
  \end{itemize}

  \begin{columns}[t]

    \begin{column}{.5\textwidth}
      \begin{codeblock}<2->{
struct Cat \{
 auto operator()(
  string const& s, int i
 ) const \{
  return s + '-' + to\_string(i);
 \}
\};

class CatWithState \{
 char c\_;
public:
 explicit CatWithState(char c)
   : c\_\{c\} \{\}
 auto operator()
 (string const& s, int i) const
 \{return s + c\_ + to\_string(i);\}
\};}\end{codeblock}

    \end{column}

    \begin{column}{.5\textwidth}
      \begin{codeblock}<2->{
accumulate(\ldots, Cat\{\});

\uncover<3->{accumulate(\ldots,
 \alert<3>{[](string const& s, int i) \{}
   return s + '-' + to\_string(i);
 \alert<3>{\}}
);}

accumulate(\ldots,CatWithState\{'-'\});

\uncover<4->{\only<4>{\alert{char c\{'-'\};}}
accumulate(\ldots,
 [\alert<4->{\only<4>{=}\only<5>{c = '-'}}](string const& s, int i) \{
  return s + \alert<4->{c} + to\_string(i);
 \}
);}}\end{codeblock}
    \end{column}

  \end{columns}
\end{frame}

\begin{frame}[fragile]{Lambda expression \insertcontinuationtext}
  The evaluation of a lambda expression produces an unnamed function object (a
  \textit{closure})
  \begin{itemize}
  \item The \texttt{operator()} corresponds to the code of the body of the
    lambda expression
  \item The data members are the captured local variables
  \end{itemize}

  \begin{columns}[t]
    \begin{column}{.5\textwidth}
      \begin{codeblock}<2->{
\uncover<4-6>{int v = 3;}

Francesco Giacomini's avatar
Francesco Giacomini committed
\uncover<2->{auto l = [}\temporal<5-6>{}{=}{v = 3}\uncover<2->{]}\uncover<3->{(\alt<-7>{int }{auto} i)\uncover<9->{\alert<9>{ -> int}}
Francesco Giacomini's avatar
Francesco Giacomini committed
\{ return i + v; \}}

\uncover<6->{auto r = l(5); // 8}}\end{codeblock}

      \uncover<7>{}
    \end{column}

    \begin{column}{.5\textwidth}
      \begin{codeblock}<2->{
\uncover<2->{class SomeUniqueName \{
  \uncover<5->{int v\_;}
 public:
Francesco Giacomini's avatar
Francesco Giacomini committed
  \uncover<5->{explicit SomeUniqueName(int v)
    : v\_\{v\} \{\}}
Francesco Giacomini's avatar
Francesco Giacomini committed
  \uncover<8->{template<typename T>}
  \alt<-8>{auto}{\alert<9>{int }} operator()\uncover<3->{(\alt<-7>{int}{T  } i)
Francesco Giacomini's avatar
Francesco Giacomini committed
  \{ return i + v\uncover<5->{\_}; \}}
\};}

\uncover<4->{int v = 3;}
\uncover<2->{auto l = SomeUniqueName\{}\uncover<5->{v}\uncover<2->{\};}
\uncover<6->{auto r = l(5); // 8}}\end{codeblock}
    \end{column}
  \end{columns}
\end{frame}

\begin{frame}[fragile]{Lambda: capturing}

  \begin{itemize}
  \item Automatic variables used in the body need to be captured
    \begin{itemize}
    \item \texttt{[]} capture nothing
    \item \texttt{[=]} capture all by value
    \item \texttt{[k]} capture \texttt{k} by value
    \item \texttt{[\&]} capture all by reference
    \item \texttt{[\&k]} capture \texttt{k} by reference
    \item \texttt{[=, \&k]} capture all by value but \texttt{k} by reference
    \item \texttt{[\&, k]} capture all by reference but \texttt{k} by value
    \end{itemize}

    \begin{columns}[t]
      \begin{column}{.5\textwidth}
        \begin{codeblock}<2->{
int v = 3;
auto l = [\only<3->{\alert<3>{\&}}v] \{\};}\end{codeblock}
      \end{column}

      \begin{column}{.5\textwidth}
        \begin{codeblock}<2->{
class SomeUniqueName \{
  int\only<3->{\alert<3>{\&}} v\_;
 public:
  explicit SomeUniqueName(int\only<3->{\alert<3>{\&}} v)
    : v\_\{v\} \{\}
  \ldots
\};

auto l = SomeUniqueName\{v\};}\end{codeblock}
      \end{column}
    \end{columns}
  \item<4-> Global variables are available without being captured
  \end{itemize}
\end{frame}

\begin{frame}{Hands-on}
  \begin{itemize}
  \item Try the code snippets
    \begin{itemize}
    \item for a quick check of the syntax use \url{http://gcc.godbolt.org/}
    \end{itemize}

  \item C++ and Memory $\rightarrow$ Algorithms
  \item Starting from \code{algo.cpp}, write code to
    \begin{itemize}
    \item sum all the elements of the vector
    \item multiply all the elements of the vector
    \item sort the vector in ascending and descending order
    \item move the even numbers to the beginning
    \item move the three central numbers to the beginning
    \item erase from the vector the elements that satisfy a predicate
    \item \ldots
    \end{itemize}
  \item How much is the overhead of a lambda?
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{Lambda: \texttt{const} and \texttt{mutable}}
  \begin{itemize}
  \item By default the call to a lambda is \texttt{const}
    \begin{itemize}
    \item Variables captured by value are not modifiable
    \end{itemize}
  \item<2-> A lambda can be declared \texttt{mutable}
  \end{itemize}

  \begin{columns}
    \begin{column}{.5\textwidth}
      \begin{codeblock}<1->{
[]\only<2->{\alert<2>{() mutable}}\only<3->{\alert<3>{ -> void}} \{\};}\end{codeblock}
    \end{column}

    \begin{column}{.5\textwidth}
      \begin{codeblock}<1->{
struct SomeUniqueName \{
  \alt<-2>{auto}{\alert<3>{void}} operator()() \only<1>{\alert{const} }\{\}
\};}\end{codeblock}
    \end{column}
  \end{columns}

  \begin{itemize}
  \item<4-> Variables captured by reference can be modified
    \begin{itemize}
    \item There is no way to capture by \texttt{const\&}
    \end{itemize}
  \end{itemize}

  \begin{codeblock}<4->
int v = 3;
[\&v] \{ ++v; \}();
assert(v == 4);\end{codeblock}

\end{frame}

\begin{frame}[fragile]{Lambda: dangling reference}

  Be careful not to have dangling references in a closure
  \begin{itemize}
  \item It's similar to a function returning a reference to a local variable
  \end{itemize}

  \begin{codeblock}
auto make\_lambda()
\{
  int v = 3;
  return [\alert{&}] \{ return v; \}; // return a closure
\}

auto l = make\_lambda();
auto d = l(); // the captured variable is dangling here\end{codeblock}

  \begin{codeblock}
auto start\_in\_thread()
\{
  int v = 3;
  return std::async([\alert{&}] \{ return v; \});
\}\end{codeblock}

\end{frame}

\begin{frame}[fragile]{\texttt{std::function}}
  \begin{itemize}
  \item Type-erased wrapper that can store and invoke any callable entity with a certain signature
    \begin{itemize}
    \item function, function object, lambda, member function
    \end{itemize}
  \item Some space and time overhead, so use only if a template parameter is not satisfactory
  \end{itemize}

  \begin{codeblock}<2->{
#include <functional>

\alert{int} sum\_squares\alert{(int} x\alert{, int} y\alert{)} \{ return x * x + y * y; \}

int main() \{
  std::vector<std::function<\alert{int(int, int)}>{}> v \{
    std::plus<>\{\},       // has a compatible operator()
    std::multiplies<>\{\}, // idem
    \&sum\_squares)
  \};
  for (int k = 10; k <= 1000; k *= 10) \{
    v.push\_back([k]\alert{(int} x\alert{, int} y\alert{)} -> \alert{int} \{ return k * x + y; \});
  \}

  for (auto const\& f : v) \{ std::cout <{}< f(4, 5) <{}< '\\n'; \}
\}}\end{codeblock}

\end{frame}

\section{Resource management}

\begin{frame}[fragile]{Weaknesses of a \texttt{T*}}

  \begin{itemize}[<+->]
  \item Critical information is not encoded in the type
    \only<.>{
      \begin{itemize}[<.>]
      \item Am I the owner of the pointee? Should I delete it?
      \item Is the pointee an object or an array of objects? of what size?
      \item Was it allocated with \texttt{new}, \texttt{malloc} or even something
        else (e.g. \texttt{fopen} returns a \texttt{FILE*})?
      \end{itemize}
    }
  \item Owning pointers are prone to leaks and double deletes
  \item Owning pointers are unsafe in presence of exceptions
  \item Runtime overhead
    \begin{itemize}
    \item<.-> dynamic allocation/deallocation
    \item<.-> indirection
    \end{itemize}
  \end{itemize}

  \begin{onlyenv}<1> % \only doesn't work for a verbatim env
    \begin{codeblock}
T* p = create\_something();\end{codeblock}
  \end{onlyenv}

  \begin{onlyenv}<2>
    \begin{codeblock}
\{
  T* p = new T\{\};
  \ldots
  // ops, forgot to delete p
\}
\{
  T* p = new T;
  \ldots
  delete p;
  \ldots
  delete p; // ops, delete again
\}\end{codeblock}
  \end{onlyenv}

  \begin{onlyenv}<3>
    \begin{codeblock}
\{
  T* p = new T;
  \ldots // potentially throwing code
  delete p;
\}\end{codeblock}
  \end{onlyenv}

\end{frame}

\begin{frame}[fragile]{Debugging memory problems}

  \begin{itemize}
  \item Valgrind is a suite of debugging and profiling tools for memory management, threading, caching, etc.
  \item Valgrind Memcheck can detect
    \begin{itemize}
    \item invalid memory accesses
    \item use of uninitialized values
    \item memory leaks
    \item bad frees
    \end{itemize}
  \item It's precise, but slow
  \end{itemize}

  \begin{onlyenv}<2>
    \begin{codeblock}
$ g++ leak.cpp
$ valgrind ./a.out
==18331== Memcheck, a memory error detector
...\end{codeblock}
  \end{onlyenv}

\end{frame}

\begin{frame}[fragile]{Debugging memory problems \insertcontinuationtext}

  \begin{itemize}
  \item \textit{Address Sanitizer} (ASan)
  \item The compiler instruments the executable so that at runtime ASan can
    catch problems similar, but not identical, to valgrind
  \item Faster than valgrind
  \end{itemize}

  \begin{onlyenv}<2>
    \begin{codeblock}
$ g++ -fsanitize=address leak.cpp
$ ./a.out

=================================================================
==18338==ERROR: LeakSanitizer: detected memory leaks
\ldots\end{codeblock}
  \end{onlyenv}

\end{frame}

\begin{frame}{Hands-on}
  \begin{itemize}
Francesco Giacomini's avatar
Francesco Giacomini committed
  \item C++ and Memory $\rightarrow$ Memory issues
Francesco Giacomini's avatar
Francesco Giacomini committed
  \item Compile, run directly and run through valgrind and/or ASan
    \begin{itemize}
    \item \code{non\_owning\_pointer.cpp}
    \item \code{array\_too\_small.cpp}
    \item \code{leak.cpp}
    \item \code{double\_delete.cpp}
    \item \code{missed\_delete.cpp}
    \end{itemize}
  \item Try and fix the problems
  \end{itemize}
\end{frame}

\begin{frame}{When to use a \code{T*}}
  \begin{itemize}
  \item To represent a \textit{link} to an object when
    \begin{itemize}
    \item the object is not owned, and
    \item the link may be null or the link can be re-bound
    \end{itemize}
  \item Mutable and immutable scenarios
    \begin{itemize}
    \item \code{T*} vs \code{T const*}
    \end{itemize}
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{When \underline{not} to use a \code{T*}}
  \begin{itemize}
  \item To represent a link to an object when
    \begin{itemize}
    \item the object is owned, or
    \item the link can never be null, and the link cannot be re-bound
    \end{itemize}
  \item Alternatives
    \begin{itemize}
    \item use a copy
    \item use a (const) reference
      \begin{codeblock}
T& tr = t1;  // tr is an alias for t1
tr = t2;     // doesn't re-bind tr, assigns t2 to t1

T* tp = &t1; // tp points to t1
tp = &t2;    // re-binds tp, it now points to t2\end{codeblock}
    \item use a resource-managing object
      \begin{itemize}
      \item \code{std::array}, \code{std::vector}, \code{std::string},
        \textit{smart pointers}, \ldots
      \end{itemize}
    \end{itemize}
  \end{itemize}
\end{frame}

\begin{frame}{Resource management}
  \begin{itemize}
  \item Dynamic memory is just one of the many types of resources manipulated by a
    program:
    \begin{itemize}
    \item thread, mutex, socket, file, \ldots
    \end{itemize}
  \item C++ offers powerful tools to manage resources
    \begin{itemize}
    \item \textit{"C++ is my favorite garbage collected language because it
      generates so little garbage"}
    \end{itemize}
  \end{itemize}

\end{frame}



\begin{frame}{Smart pointers}
  \begin{itemize}
  \item Objects that behave like pointers, but also manage the lifetime of the pointee
  \item Leverage the RAII idiom
    \begin{itemize}
    \item Resource Acquisition Is Initialization
    \item Resource (e.g. memory) is acquired in the constructor
    \item Resource (e.g. memory) is released in the destructor
    \end{itemize}
  \item Importance of how the destructor is designed in C++
    \begin{itemize}
    \item deterministic: guaranteed execution at the end of the scope
    \item order of execution opposite to order of construction
    \end{itemize}
  \item Guaranteed no leak nor double release, even in presence of exceptions
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{Smart pointers \insertcontinuationtext}
  \begin{codeblock}
template<typename Pointee>
class SmartPointer \{
  Pointee* m\_p;
 public:
  explicit SmartPointer(Pointee* p): m\_p\{p\} \{\}
  \~SmartPointer() \{ delete m\_p; \}
  \visible<3->{Pointee* operator\alert<3>{->}() \{ return m\_p; \}
  Pointee& operator\alert<3>{*}() \{ return *m\_p; \}}
  \visible<4->{\ldots}
\};

class Complex \{ \ldots \};

\{
  SmartPointer<Complex> sp\{new Complex\{1., 2.\}\};
  \visible<2->{sp\alert<2-3>{->}real();
  (\alert<2-3>{*}sp).real();}
\}\end{codeblock}

At the end of the scope (i.e. at the closing \code{\}}) \code{sp} is destroyed
and its destructor \code{delete}s the pointee

\end{frame}

\begin{frame}[fragile]{\texttt{std::unique\_ptr<T>}}

  Standard smart pointer

  \begin{itemize}
  \item Exclusive ownership
  \item No space nor time overhead
  \item Non-copyable, movable
  \end{itemize}

  \begin{codeblock}<2->{
struct X \{
  \ldots
  X(T1, T2);
\};

void use(std::unique\_ptr<X> px); \uncover<6>{    \alert{// by value}}

\uncover<3->{std::unique\_ptr<X> x\{new X\{t1, t2\}\}; // explicit new}