$30 off During Our Annual Pro Sale. View Details »

C++11

Avatar for dhara dhara
January 18, 2014

 C++11

C++11 is the most recent version of the standard of the C++ programming language.From lambda expressions to range based for loops to null pointer constants,this is a basic introduction to the new standard.

Avatar for dhara

dhara

January 18, 2014
Tweet

Other Decks in Programming

Transcript

  1. History and Vocabulary 1998: ISO C++ Standard officially adopted (“C++98”).776

    pages. 2003: TC1 (“Technical Corrigendum 1”) published (“C++03”).Bug fixes for C++98. 2005: TR1 (Library “Technical Report 1”) published.14 likely new components for the std library. 2009: Selected “C++0x” features became commonly availabile. 2011: C++0x ratified ⇒ “C++11”.--1353 pages. 2013: Full C++14 draft adopted.--1374 pages. 2014: Revised C++ Standard (minor). 2017?: Revised C++ Standard (major).
  2. Features  Auto  Nullptr  Lambda expressions  Range

    Based for loop  Initializer list  Inherit Constructors  Move Constructors  Enhanced enums  Static_assert  Explicit keyword
  3. C++11 - feature use auto • auto used to declare

    types that are deduced from context, is no longer a storage specifier. auto x1 = 10; // x1: int • Type deduction for auto is similar to that for template parameters: template<typename T> void f(T t); f(expr); // deduce t’s type from expr auto v = expr; // do essentially the same thing for v’s type • Both direct and copy initialization syntaxes are permitted. // For auto, both syntaxes have the same meaning. auto v1(expr); // direct initialization syntax auto v2 = expr; // copy initialization syntax
  4. More auto examples std::map<int, std::string> m; auto i1 = m.begin();

    // i1: std::map<int, std::string>::iterator const/volatile and reference/pointer adornments may be added: const auto *x2 = &x1; // x2: const int* const auto& i2 = m; // i2: const std::map<int, std::string>& To get a const_iterator, use the new cbegin container function: auto ci = m.cbegin(); // ci: std::map<int, std::string>::const_iterator cend, crbegin, and crend exist, too.
  5. nullptr,new keyword, Indicates a null pointer! const char *p =

    nullptr; // p is null int i = nullptr; // error! Traditional uses of 0 and NULL remain valid: int *p1 = nullptr; // p1 is null int *p2 = 0; // p2 is null int *p3 = NULL; // p3 is null if (p1 == p2 && p1 == p3) // code compiles, test succeeds Only nullptr is unambiguously a pointer: void f(int *ptr); // overloading on ptr and int void f(int val); f(nullptr); // calls f(int*); f(0); // calls f(int)
  6. C++03 C++11 int a[] = { 1, 2, 3, 4,

    5 }; vector<int> v; for( int i = 1; i <= 5; ++i ) v.push_back(i); int a[] = { 1, 2, 3, 4, 5 }; vector<int> v = { 1, 2, 3, 4, 5 }; map<int, string> labels; labels.insert(make_pair(1, “On”)); labels.insert(make_pair(2, “Off”)); labels.insert(make_pair(3,“Reboot”)); map<int, string> labels { { 1 , "Open" }, { 2 , "Close" }, { 3 , "Reboot" } }; Uniform Initialization
  7. std::initializer_list vector<int> v = { 1, 2, 3, 4, 5}//How

    to make this work? vector<int> v = { 1, 2, 3, 4, 5 }; //vector(initializer_list<T> args) is called template<class T> class vector{ vector(initializer_list<T> args) { for(auto it = begin(args); it != end(args); ++it) push_back(*it); } //… }; what is initializer_list<T> ? vector<int> v{1,2,3,4,5};//list- initialization v = {1,2,3,4,5};//assignment expression f({1,2,3,4,5});//function call for (int x : {1, 2, 3})//ranged for loop cout << x << endl;
  8. Enhanced enums Specification of underlying type now permitted: enum class

    Color:int { red, green, blue }; enum class Alert { green, yellow, red }; //error if ‘red’ been redefined in C++98 class indicates that each enum type is different and not comparable to other enum types. Color::red != Alert::red; enum Color { red, green, blue }; // fine, same meaning as in C++98
  9. Strongly typed enums: enum classes enum class Elevation: char {

    low, high }; // underlying type = char enum class Voltage { low, high }; // underlying type = int(defaults) Elevation e = low; // error! no “low” in scope Elevation e = Elevation::low; // fine int x = Voltage::high; // error! if (e) ... // error!
  10. Range Based for Loops Looping over a container can take

    this streamlined form: std::vector<int> v; for (int i:v) std::cout << i; // iteratively set ito every element in v The iterating variable may also be a reference: for (int& i : v) std::cout << ++i;// increment and print everything in v auto, const, and volatile are allowed: for (auto i : v) std::cout << i; // same as above for (auto& i : v) std::cout << ++i; // ditto for (volatile int i : v) someOtherFunc(i); // or "volatile auto i"
  11. “>>”as Nested Template Closer “>>” now closes a nested template

    when possible: std::vector<std::list<int>> vi1; // fine in C++11, error in C++98 The C++98 “extra space” approach remains valid: std::vector<std::list<int> > vi2; // fine in C++11 and C++98 For a shift operation, use parentheses: I.e., “>>” now treated like “>” during template parsing. const int n = … ; // n, m are compile const int m = … ; // time constants std::list<std::array<int, n>>2 >> L1; // error in C++98: 2 shifts; // error in C++11: 1st “>>” closes both templates std::list<std::array<int, (n>>2) >> L2; // fine in C++11, error in C++98 (2 shifts)
  12. Lambda C++11 Taken from LISP Unnamed function [](int i){cout <<i

    << endl;} //goes where the function object is required [] (int n) { return n * 5.5; }//double // deduces the return value –no return void [] (int n) -> int { return ++n; } //explicit
  13. Lambda Expressions // A Fibonacci generator functor class GenerateFibonacci {

    private: int penultimate_, last_; public: GenerateFibonacci() : penultimate_(0), last_(1) {}; int operator()(){ int current = penultimate_ + last_; penultimate_ = last_; return last_ = current; } }; void printIfOdd(int n) { if (n%2) cout << n << " is odd." << endl; } int main() { list<int> l(20); generate(begin(l), end(l), GenerateFibonacci()); for_each(begin(l), end(l), printIfOdd); return 0; }
  14. Lambda Expressions in action int main() { list<int> l(20); generate(begin(l),

    end(l), [] () { static int penultimate(0), last(1); int current = penultimate + last; penultimate = last; return last = current; } ); // likewise, we do the same with function printIfOdd(int). for_each(begin(l), end(l), [] (int n) { if (n%2) cout << n << " is odd." << endl; }); return 0; } Output: // odd elements (1, 3, 5, 13, 21, 55, ...)
  15. My implementation of array! my_container template <class T, int n>

    class my_container { public: my_container(){ a = new T[n];} ~my_container{ delete[] a;} private: T* a; };
  16. Delegate construction – new C++11 explicit my_container(T *b):my_container() { for(int

    i = 0; i <n ; ++i) a[i] = b[i]; } Suppress automatic coercion my_container(const my_container &b):my_container(){ for(int i = 0; i <n ; ++i) a[i] = b.a[i];} Ordinary copy constructor –again with constructor delegation.
  17. “Move “ Constructor my_container(my_container &&b)noexcept { a = b.a; b.a

    = nullptr; } Contents are “moved” not copied Note new use of && to mean an rvalue address
  18. Move assignment my_container& operator=(my_container&& b)noexcept{ a = b.a; b.a =

    nullptr; return *this; } Non-copying – move assignment; rhs destroyed
  19. Efficient swap void swap(my_container &b) { my_container temp = move(b);

    //will not be used b = move(*this); *this = move(temp); } The std::move() static_cast<T&&>(t) -destructive assignment More efficient because all the assignments are referential
  20. Static assert • static_assert ( bool_constexpr , string ) bool_constexpr

    - a boolean constant expression evaluated at compile time • string: string literal that will be a compiler error if bool_constexpr is false #include <type_traits> template <class T> void swap( T& a, T& b) { static_assert(std::is_copy_constructible<T>::value,"Swap requires copying"); auto c = b; //expectation of copy construction b = a; a = c;}
  21. Some New Libraries C++11 tuple -pair and more array -fixed

    length array container forward_list -single pointer list unordered_map, unordered_set -hashing thread -uniform thread interface Regex -regular expressions type_traits -type characteristics
  22. std::tuple C++11 Python tuple<int,float,string> t(1,2.f,”text”); int x = get<0>(t); float

    y = get<1>(t); string z = get<2>(t); t = (1,2.0,’text’) x = t[0] y = t[1] z = t[2] int myint; char mychar; tuple<int,float,char> mytuple; // packing values into tuple mytuple = make_tuple (10, 2.6, 'a'); // unpacking tuple into variables tie(myint, ignore, mychar) = mytuple; # packing values into tuple mytuple = (10, 2.6, 'a') # unpacking tuple into variables myint, _, mychar = mytuple int a = 5; int b = 6; tie(b, a) = make_tuple(a, b); a = 5 b = 6 b,a = a,b
  23. Use of regex   #include <iostream>   #include <string>  

    #include <regex>   using namespace std;   int main() {   string fnames[] = {“ira.txt", “data.txt", “ira2.txt", “a.out"};   regex txt_regex("[a-z]+\\.txt");   for (int i = 0; i < 4; ++i)   cout << fnames[i] << ":" << regex_match(fnames[i], txt_regex) << '\n';    }
  24. Quiz! What’s the output ? string fnames[] = {“abc.txt", “data.txt",

    “abc2.txt", “a.out"}; regex txt_regex("[a-z]+\\.txt"); for (int i = 0; i < 4; ++i) cout << fnames[i] << ":" << regex_match(fnames[i], txt_regex) << '\n';
  25. Some final C++ 11 points #include <iostream> #include <string> class

    simple{ public: simple() = default; //compiler generated simple(double x) = delete; //surpressed conversion constructor simple(int x , int y ): p(x),q(y){} simple(int x ): simple(x, 1){} //delegate constructor simple(const simple& x ): simple(x.p, x.q){} //delegate constructor simple(simple&& x ): simple(x.p, x.q){ x.p = x.q =0;} //move semantics private: int p = 0, q = 1; //default initializer can be overriden }; class rational: public simple{ public: using simple::simple; //implicitly declares constructors //but uses base   };