// This is an improved version of combo3 that minimizes copying. We tell the // vector to make room for 4 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 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(const vector & v) { cout << "entering foreach loop" << endl; for (const combo & c : v) { cout << c.get_value() << " " << c.get_text() << endl; } } int main() { combo c(42, "hello"); cout << endl; vector v; v.reserve(4); v.emplace_back(3, "bar"); v.emplace_back(15, "baz"); v.emplace_back(7, "mumble"); v.emplace_back(c.get_value(), c.get_text()); cout << "calling print:" << endl; print(v); return 0; }