Part III Using swap When using moveFrom , if a new data member is added, both swap and moveFrom have to be modified. To avoid that, one can write the move constructor and move assignment operator with a default constructor and the swap function. class Bank { private : Bank ( ) = default ; } Now cleanup() and moveFrom() can be removed. The destructor handles the code from cleanup . The code is as follows: Bank :: Bank ( Bank && src ) noexcept : Bank ( ) { swap ( * this , src ) ; //Default constructor creates *this. } Bank & Bank :: operator = ( Bank && rhs ) noexcept { Bank temp ( std :: move ( rhs ) ) //Need std::move because rhs is named swap ( * this , temp ) ; return * this ; } Implementing swap with move semantics Using move semantics improves the performance of swap as seen below: void swa...
C-style strings C style strings should be avoided except when interfacing with C libraries. C string library functions provide no bounds checking and memory allocation support. They are represented as an array of characters. Last character of the string is the null character \0 , so that code that uses the string knows where it ends. The space needed for a string is always one more than the number of readable characters. String Literals Strings written with quotes around them are string literals. They are stored in a read-only part of memory. Because they are stored in readonly sections, attempting to modify string literals is undefined behavior . Example: char * str = "world" ; str [ 0 ] = 'y' ; //undefined behavior If the code respected the standard and assigned the string literal to const char* , the compiler will catch attempts to modify string literals: const char * str = "world" ; str [ 0 ] = 'k' ; //compiler will f...
Introduction to STL Containers expose the iterator interface and the Algorithms work on the iterators . std::vector Example of iterating through a vector is below. Iterator behaves like an enhanced pointer. # include <iostream> using namespace std ; int main ( ) { vector < int > nums ; nums . push_back ( 3 ) ; nums . push_back ( 1 ) ; nums . push_back ( 2 ) ; vector < int > :: iterator first = nums . begin ( ) ; vector < int > :: iterator onePastLast = nums . end ( ) ; for ( vector < int > :: iterator i = first ; i != onePastLast ; i ++ ) { cout << "Next Element is " << * i << endl ; } //sorting a vector sort ( first , onePastLast ) ; //after sorting 1,2,3 } Types of containers Sequence containers(array and linked list): vector, deque, list, forward list, and array Associative containers (binary tree) : set, multiset, map...
Comments
Post a Comment