/* How is a data structure like vector defined? */ #include #include using namespace std; template struct myvector{ T* V; int len; myvector(int n) {len=n; V = new T[n];} myvector(initializer_list M) { len = M.size(); V = new T[len]; int i=0; for (T x:M) V[i++] = x; } ~myvector() { if (V) delete[] V; } // destructor T& operator [] (int i) {return V[i];} int size() { return len; } // the default copy semantics copies just the pointer when a copy // occurs (a = b). This is not a good idea because when the // destructors of the two copies of myvector are called, the same // data is deleted twice. // define custom copy semantics myvector(const myvector& other) { // copy constructor len = other.len; V = new T[len]; // recreate another array on heap for(int i=0;i& operator =(const myvector& other) { // copy = operator len = other.len; V = new T[len]; // recreate another array on heap for(int i=0;i&& other) { // MOVE constructor len = other.len; if (V) delete[] V; V = other.V; other.V = nullptr; other.len = 0; } void operator =(myvector&& other) { // MOVE = operator len = other.len; if (V) delete[] V; V = other.V; other.V = nullptr; other.len = 0; } // push_back requires reallocating the vector.. }; int main() { vector v1{2,4,6,8}; vector v2 = v1; // is the data copied, or just a pointer copied? v2[3] = 9; cout << v1[3] << " and " << v2[3] << endl; myvector m1{1,3,5,7}; myvector m2 = m1; m2[3] = 9; cout << m2[3] << endl; cout << m1[3] << endl; return 0; } // program illustrating custom copy semantics in traditional C++