FAQ 22.02 What will happen if constructor initialization lists are not used?

graphics/new_icon.gif

Initialization lists are usually a performance issue, although there are cases when initialization lists impact correctness (see FAQ 22.03 and 22.04). In some cases the code of a constructor can be three times slower if initialization lists are not used. For example, consider the following Person class.

 #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 { } 

(1) Good: Use initialization rather than assignment

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 

(1) Inefficient: Assignment used rather than initialization

Conclusion: All other things being equal, code will run faster with initialization lists than with assignment.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net