// Example of using our combo class with a vector. This version is highly // inefficient. The print function in particular is badly written because it // uses a value parameter (which makes an independent copy of the vector) and // it uses a simple variable in the foreach loop that also makes a copy of each // combo object. We were able to see lots of messages about objects being // constructed, copied, and destroyed. #include #include #include using namespace std; class combo { public: combo(int initial_value = 0, const string & initial_text = "foo") { value = initial_value; text = new string(initial_text); cout << "in regular constructor" << endl; } // copy constructor combo(const combo & rhs) { value = rhs.value; // default is shallow copy: text = rhs.text text = new string(*rhs.text); cout << "in copy constructor" << endl; } // assigment operator combo & operator=(const combo & rhs) { if (this != &rhs) { value = rhs.value; // default is shallow copy: text = rhs.text *text = *rhs.text; } cout << "in assignment operator" << endl; return *this; } // destructor ~combo() { delete text; cout << "in destructor with value = " << value << endl; } int get_value() const { return value; } const string & get_text() const { return *text; } private: int value; string * text; }; void print(vector v) { cout << "entering foreach loop" << endl; for (combo c : v) { cout << c.get_value() << " " << c.get_text() << endl; } } int main() { vector v; v.push_back(combo(3, "bar")); v.push_back(combo(15, "baz")); v.push_back(combo(7, "mumble")); cout << "calling print:" << endl; print(v); return 0; }