COMS W4995 C++ Deep Dive for C Programmers

Vec Class Template

Lecture outline

  1. turning IntArray into a class template

    • change IntArray to Vec
    • change data type to T
    • add template <typename T>
    • push_back() takes const T& now
    • change operator<<() to a function template
    • need to specify element type when declaring Vec – Vec<int> and Vec<string>
  2. Value semantics of STL containers

    • all STL containers (i.e., C++ standard library containers) hold their elements by value
  3. Stack & heap diagram for the following sequence of code:

    Vec<MyString> v;
    v.push_back("abc");
    v.push_back("def");
    MyString s{"xyz"};
    v.push_back(s);
    
    • Vec<MyString> holds MyString objects by value

    • There is no copy construction of MyString objects

      • MyString objects are default-constructed when capacity increases
      • push_back() invokes MyString::operator=()
  4. Placement new

    • std::vector does not default-construct elements on empty slots
    • It simply allocates memory to hold future objects
    • How does vector::push_back() construct an object at existing memory?
    • Placement new syntax:

        new (p) MyString{"xyz"};
      
  5. Strong Exception Guarantee

    • IntArray -> Vec changes
    • std::vector move vs. copy