#include <new> #include <string> using namespace std; class Person { public: Person(const string& name, const string& suffix) throw(bad_alloc); // ... private: string name_; }; The following implementation of the constructor initializes member object name_ using an initialization list. From a performance perspective, it is important to note that the result of the + operator is constructed directly inside member object name_. A temporary object is not needed in this case, and most compilers do not produce an extra temporary object. This typically requires one allocation of memory from the heap and one copy of the data from each string. Person::Person(const string& name, const string& suffix) throw(bad_alloc) : name_(name + suffix) <-- 1 { }
In contrast, the following constructor sets up member object name_ using assignment. In this case the default constructor (see FAQ 20.08) may have allocated a small amount of memory (many string classes store a '\0' byte even in cases when the string is empty); then that memory is immediately discarded in the assignment operator. In addition, the compiler will probably have to create a temporary object, and this temporary object is passed into the name_ object's assignment operator; then the temporary is destructed at the ;. That's inefficient. All together, this constructor might make three calls to the memory allocation routines (two allocations, one deallocation) and might copy the string's data twice (once into the temporary and once into name_). Person::Person(const string& name, const string& suffix) throw(bad_alloc) { name_ = name + suffix; } <-- 1
Conclusion: All other things being equal, code will run faster with initialization lists than with assignment. |