// This is an improved version of combo3 that minimizes copying. We // tell the vector to make room for 3 values after we construct it and // we pass the vector as a const reference parameter with the foreach // loop also using a const reference for each item. We use the // emplace_back function of the vector class where we provide the // parameters to use for constructing a combo object. Then the vector // does the constructing, which elminates the need for copying. #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(const vector & v) { cout << "entering foreach loop" << endl; for (const combo & c : v) { cout << c.get_value() << " " << c.get_text() << endl; } } int main() { vector v; v.reserve(3); v.emplace_back(3, "bar"); v.emplace_back(15, "baz"); v.emplace_back(7, "mumble"); cout << "calling print:" << endl; print(v); return 0; }