// test_safev.cc first of sequence, shows UNsafe // test_safe2.cpp adds copy constructor, 'explicit' // AND operator= // all three are needed to be safe with pointers !!! // test_safev.cpp shows the STL protects you // use STL data structures and get safety that way #include #include using namespace std; int main() { cout << "test_safev.cc is SAFE" << endl; class safev { public: safev(){i=1;} safev(safev & x){*this = x;} ~safev(){} // do not need 'delete', only objects void set(int ii){i=ii;} int get(){return i;} void set(vector &aa){a=aa;} // vector makes this safe void set(int index, int val){ a[index]=val;} int get(int index){return a[index];} private: int i; // single variables OK vector a; // good news, is safe }; vector v1; v1.push_back(1); v1.push_back(2); v1.push_back(3); safev U1; safev U2; // try{ // cout << "illegal index" << U1.get(1) << endl; // }catch(...){cout << "caught illegal index." << endl;} U1.set(v1); cout << "index 1 of U1 is 2== " << U1.get(1) << endl; U2=U1; // does copy GOOD cout << "index 1 of U2 is 2== " << U2.get(1) << endl; safev U3 = U1; // does copy GOOD cout << "index 1 of U3 is 2== " << U3.get(1) << endl; safev U4(U1); // does copy GOOD cout << "index 1 of U4 is 2== " << U4.get(1) << endl; cout << "now U1.set(1,5) does not change U2, U3 and U4" << endl; U1.set(1,5); // set index 1 to value 5 cout << "index 1 of U1 is 5== " << U1.get(1) << endl; cout << "index 1 of U2 is 2== " << U2.get(1) << " GOOD" << endl; cout << "index 1 of U3 is 2== " << U3.get(1) << " GOOD" << endl; cout << "index 1 of U4 is 2== " << U4.get(1) << " GOOD" << endl; cout << "end test_safev" << endl; return 0; } //Output from executing program // test_safev.cc is SAFE // index 1 of U1 is 2== 2 // index 1 of U2 is 2== 2 // index 1 of U3 is 2== 2 // index 1 of U4 is 2== 2 // now U1.set(1,5) does not change U2, U3 and U4 // index 1 of U1 is 5== 5 // index 1 of U2 is 2== 2 GOOD // index 1 of U3 is 2== 2 GOOD // index 1 of U4 is 2== 2 GOOD // end test_safev