// 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 initValue = 0, const string & initText = "foo") { value = initValue; text = new string(initText); cout << "in main constructor" << endl; } int get_value() const { return value; } const string & get_text() const { return *text; } combo(const combo & rhs) { value = rhs.value; text = new string(*rhs.text); cout << "in copy constructor" << endl; } ~combo() { delete text; cout << "in destructor" << endl; } combo & operator=(const combo & rhs) { if (this != &rhs) { value = rhs.value; *text = *rhs.text; } cout << "in assignment operator" << endl; return *this; } 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; }