Title | CS211 611 lecture 220 |
---|---|
Author | Calvie Thang |
Course | Object-Oriented Programming In C++ |
Institution | Queens College CUNY |
Pages | 23 |
File Size | 164.3 KB |
File Type | |
Total Downloads | 58 |
Total Views | 171 |
Download CS211 611 lecture 220 PDF
Queens College, CUNY, Department of Computer Science Object Oriented Programming in C++ Sateesh Mane c Sateesh R. Mane 2019 August 10, 2019
Move semantics • In this lecture we shall learn about various optimizations the compiler performs. • They go by the name of move semantics. • Move semantics were introduced in C++11. • We shall study the move constructor and move assignment operator. • These are a new type of constructor and assignment operator in addition to those we have already studied (default/non-default/copy constructors and assignment operator). • If we do not write a move constructor and/or a move assignment operator, modern C++ compilers will write them automatically for us. • As always, the automatically generated versions may not always do what we want. • The command std::move can be used to force the compiler to invoke move semantics. • Note that the purpose of move semantics is for optimization. • If move semantics are not employed, the execution speed may be slower and dynamic memory allocation may be larger, but the result of the program execution is the same.
1
1
Introduction • Let us write a simple class and some functions and a main program as follows. • The class constructors allocate dynamic memory just to necessitate a deep copy. class IArray { private: int *ip, sz; public: int len() const { return sz; } const int* ptr() const { return ip; } int* ptr() { return ip; } IArray(int n, int x); IArray(const IArray &orig); IArray& operator=(const IArray &rhs); ~IArray() { delete [] ip; }
// accessor // accessor // mutator // // // //
non-default copy assign destroy
}; IArray::IArray(int n, int x) : sz(std::max(n,1)) { ip = new int[sz]; for (int i = 0; i < sz; ++i) ip[i] = x; } IArray::IArray(const IArray &orig) : sz(orig.sz), ip(nullptr) { if (sz > 0) { ip = new int[sz]; for (int i = 0; i < sz; ++i) ip[i] = orig.ip[i]; } } IArray& IArray::operator=(const IArray &rhs) { if (this == &rhs) return *this; delete [] ip; ip = nullptr; sz = rhs.sz; if (sz > 0) { ip = new int[sz]; for (int i = 0; i < sz; ++i) ip[i] = rhs.ip[i]; } return *this; } 2
• Here is a main program and function to use the class IArray. #include using namespace std; class IArray // etc void print(const IArray &p) { const int *q = p.ptr(); if (q == nullptr) cout...